Stephen Jacob
Stephen Jacob

Reputation: 901

fstream not creating new file

I am trying to learn dynamic file access. My code is as follows:

int main()
{
    dtbrec xrec; // class object
    fstream flh;

    // Doesn't create a new file unless ios::trunc is also given.
    flh.open("database.txt", ios::in | ios::out | ios::binary);

    flh.seekp(0,ios::end);
    xrec.getdata();
    flh.write((char*)&xrec, sizeof(dtbrec));

    flh.close();
}

I thought that fstream by default creates a new file 'database.txt' if it doesn't exist. Any ideas as to what could be wrong?

Upvotes: 3

Views: 29069

Answers (3)

Hunter Keene
Hunter Keene

Reputation: 11

In addition to what Stephen Jacob said, I found that I needed to do

f.open("file.txt", fstream::trunc | fstream::out);

on windows in order to actually generate the file. Just doing trunc didn't work.

Upvotes: 1

Stephen Jacob
Stephen Jacob

Reputation: 901

Some pointers about fstream:

a. If you are using a back slash to specify the directory such as when using fstream f;

f.open( "folder\file", ios::out);

it won't work, a back slash has to be preceded by a backslash, so the correct way would be:

f.open( "folder\\file", ios::out);

b. If you want to create a new file, this won't work:

f.open("file.txt", ios::in | ios::out | ios::binary);

the correct way would be to first create the file, using either ios::out or ios::trunc

f.open("file.txt". ios::out) or f.open("file.txt", ios::trunc);

and then

f.open("file.txt", ios::in | ios::out | ios::binary);

c. Finally, it could be in this order as specified in this answer, fstream not creating file

Basically ios::in requires to already have an existing file.

Upvotes: 21

built1n
built1n

Reputation: 1546

Try using ofstream, it automatically creates a file, if it does not already exist. Or, if you want to do both input, and output on the stream, try using fstream, but you need not specify ios::in|ios::out|ios::binary, because fstream automatically sets it up for you.

Upvotes: 5

Related Questions