简体   繁体   English

Mac OS上的C ++ std :: fstream行为

[英]c++ std::fstream behaviour on MacOS

On MacOS with gcc4.2 should the following code create a new file if none exists? 在具有gcc4.2的MacOS上,以下代码是否应创建一个新文件(如果不存在)?

#include <fstream>

void test () {
    std::fstream file ("myfile.txt", std::ios::in | std::ios::out);
}

By my logic it should, either open up an existing file for read/writing or create a new empty file for read/writing. 按照我的逻辑,应该打开一个现有文件进行读取/写入,或者创建一个新的空文件进行读取/写入。 But the behaviour I get is that it will not create a new file if 'myfile.txt' does not exist. 但是我得到的行为是,如果'myfile.txt'不存在,它将不会创建新文件。

How do I get the same behavior as fopen("myfile.txt", "r+"); 如何获得与fopen(“ myfile.txt”,“ r +”)相同的行为; ?

Furthermore, 此外,

#include <fstream>

void test () {
    std::ofstream file ("myfile.txt", std::ios::in | std::ios::out);
}

Will always truncate an existing file... 始终截断现有文件...

Is this the standard behavior? 这是标准行为吗?

First of all, I have no idea why you think that fopen("r+") creates a file if it doesn't exist - according to ISO C & C++, it does not, it just opens an existing file for read/write. 首先,我不知道为什么您会认为fopen("r+")创建一个文件(如果不存在)-根据ISO C&C ++,它不会,它只是打开一个现有文件进行读取/写入。 If you want to create a file with fopen , you use "w+" . 如果要使用fopen创建文件,请使用"w+"

For streams, you just specify trunc : 对于流,只需指定trunc

std::ofstream file ("myfile.txt",
    std::ios::in | std::ios::out | std::ios::trunc);

However, both this and fopen("w+") will truncate the file. 但是,this和fopen("w+")都会截断文件。 There's no standard way to open the file without truncating if it exists, but create it if it does not exist in a single call. 没有标准的方法可以在不截断文件的情况下打开文件,但是如果文件在单个调用中不存在,则可以创建文件。 At best you can try to open, check for failure, and then try to create/truncate; 充其量您可以尝试打开,检查是否失败,然后尝试创建/截断; but this may lead to a race condition if file is created by another process after the check but before truncation. 但是如果在检查之后但在截断之前通过另一个进程创建了文件,则可能导致争用情况。

In POSIX, you can use open with O_CREAT and without O_TRUNC . 在POSIX中,可以将openO_CREAT一起使用,而无需O_TRUNC

For the first case, you have specified that you are BOTH reading from and writing to the file. 对于第一种情况,您已经指定要同时读取和写入文件。 Hence, it will fail, if the file does not already exist. 因此,如果文件不存在,它将失败。 You could try to use two separate streams (one for reading and the other for writing), and construct the output stream, first. 您可以尝试使用两个单独的流(一个用于读取,另一个用于写入),并首先构造输出流。 As for the second case, you can use "std::ios::app" (open in append mode) to prevent truncation. 至于第二种情况,可以使用“ std :: ios :: app”(以追加模式打开)来防止截断。 [Tested with Mac OS X 10.4.11, GCC 4.0.1] [在Mac OS X 10.4.11和GCC 4.0.1上进行了测试]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM