3

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?

tambre
  • 4,625
  • 4
  • 42
  • 55
Stephen Jacob
  • 889
  • 1
  • 15
  • 33

3 Answers3

20

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.

Community
  • 1
  • 1
Stephen Jacob
  • 889
  • 1
  • 15
  • 33
  • 1
    Your examples show forward slashes, not backslashes. You do not need to escape forward slashes. – Buge Jul 31 '14 at 17:52
  • Thanks Buge I have edited it, I used backlash when I was learning about fstream. While I am aware and predominantly using forward slash now, I will not like to edit the content (using backslashes) as I personally believe that initially while learning fstream, this post may be useful especially to a newbie, however your comment can prove useful to them as well – Stephen Jacob Aug 01 '14 at 03:24
3

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.

built1n
  • 1,518
  • 14
  • 25
0

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.