fstream won't create a file

raphnguyen picture raphnguyen · Mar 27, 2013 · Viewed 99.9k times · Source

I'm simply trying to create a text file if it does not exist and I can't seem to get fstream to do this.

#include <fstream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt");
    file << "test";
    file.close();
}

Do I need to specify anything in the open() function in order to get it to create the file? I've read that you can't specify ios::in as that will expect an already existing file to be there, but I'm unsure if other parameters need to be specified for a file that does not already exist.

Answer

haitaka picture haitaka · Mar 27, 2013

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out);

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/