29

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.

raphnguyen
  • 3,565
  • 18
  • 56
  • 74

3 Answers3

27

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/

haitaka
  • 1,832
  • 12
  • 21
  • 1
    Am I not allowed to do `file.open("test.txt", fstream::in | fstream::out | fstream::binary);` on a file that does not yet exist? – raphnguyen Mar 27 '13 at 19:29
  • 6
    You should add fstream::trunc if you want fstream::in to work on an non-existent file. – haitaka Mar 27 '13 at 19:41
  • 1
    @haitaka Is it a workaround? Because it seems illogical: in order to make a stream from a created file `in` I have to truncate the stream. – Oleksa Aug 20 '20 at 18:40
17

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
ceruleus
  • 704
  • 3
  • 12
3

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}
Ritesh Kumar Gupta
  • 5,055
  • 7
  • 45
  • 71