gpt4 book ai didi

C++ ofstream 相当于 Win32 CreateFile with CREATE_NEW

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:42 25 4
gpt4 key购买 nike

在一个应用程序中,我想确保我正在编写一个全新的(二进制)文件。在 Win32 编程中,我知道我可以用 CreateFile 做到这一点使用 CREATE_NEW,但我无法找到纯 C++ 标准方法。

Creates a new file, only if it does not already exist.
If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).
If the specified file does not exist and is a valid path to a writable location, a new file is created.

我尝试使用 std::ios::out | std::ios::二进制 | std::ios::ate 然后看看 tellp 是否给了我文件的开头,但除了明显的情况,这仍然会覆盖一个空文件,它似乎也无论如何都要截断一个非空文件,就像我使用 std::ios::trunc...

这是在 VS2013 上,虽然我认为这不是编译器/库错误。

最佳答案

C++ 标准没有保证新文件的 API。在未指定 std::ios_base::app 的情况下以只写模式打开现有文件时,它会被截断(与是否使用 std::ios_base::trunc 无关) .我不知道 Windows,但在 POSIX 上,这将保留原始 inode,并且已经打开文件的进程仍然可以访问它。

如果获取一个打开的空文件而不是一个新文件就足够了,则省略 std::ios_base::instd::ios_base::app应该可以解决问题(请注意,打开 std::fstreamstd::ifstream 会隐式添加 std::ios_base::in) .

关于C++ ofstream 相当于 Win32 CreateFile with CREATE_NEW,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27706865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com