tags:

views:

327

answers:

2

On MacOS with gcc4.2 should the following code create a new file if none exists?

#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.

How do I get the same behavior as 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?

+3  A: 

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. If you want to create a file with fopen, you use "w+".

For streams, you just specify 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. 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.

Pavel Minaev
Your right, I was mistaken. I was thinking of POSIX, instead of "r+". Appologies for the stupid question :).
Akusete
A: 

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. [Tested with Mac OS X 10.4.11, GCC 4.0.1]

Michael Aaron Safyan