Creating files with fstream

I'm having problems in creating files with fstream.
The following code piece creates the "change.vi" file, but doesn't create "file.txt".
In brief,I can create files with ofstream but not with fstream. What am I missing?

1
2
3
4
5
6
7
8
9
        fstream myfile1;
        ofstream myfile2;
        myfile1.open("file.txt", fstream::in | fstream::out);
        myfile2.open("change.vi");

        if(!myfile1.is_open() || !myfile2.is_open() ){
                cerr << "File or files cannot be opened!" << endl;
                return 0;
        }
Last edited on
You're not missing anything. Since input from a newly created file is not possible, if you try to open a non existent file with an input flag the operation fails.
Hmm ok, I got the idea.
As a workaround, the following can be used.

1
2
3
4
5
6
7
8
9
 fstream myfile1;
        ofstream myfile2;
        myfile1.open("file.txt", fstream::in | fstream::out | fstream::trunc);
        myfile2.open("change.vi");

        if(!myfile1.is_open() || !myfile2.is_open() ){
                cerr << "File or files cannot be opened!" << endl;
                return 0;
        }
Topic archived. No new replies allowed.