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?
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 withfopen, you use"w+".For streams, you just specify
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
openwithO_CREATand withoutO_TRUNC.