Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 877
Stephen Jacob Avatar asked Feb 06 '26 14:02

Stephen Jacob


2 Answers

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.

like image 74
Stephen Jacob Avatar answered Feb 09 '26 07:02

Stephen Jacob


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.

like image 40
built1n Avatar answered Feb 09 '26 07:02

built1n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!