ofstream object failing to open file

All I'm doing is creating an ofstream object called outFile and then opening a text file and writing to it. For some reason it fails, however the program opens it for reading and writing before this particular code and does not fail.
The code is as follows:

1
2
3
4
5
6
7
8
9
10
11
outFile.open("users.txt", ios::binary);
   if(outFile.fail())
      {
      cout << "\n\nCOULD NOT SAVE CHANGES!\n";
      system("pause");
      return false;               
      }
      
for(it = allUsers.begin(); it != allUsers.end(); it++)
   outFile.write((char*) &(*it), sizeof(User));   //Write new user to file
outFile.close();


This code is identical to the code used to write to this file earlier in the program. outFile.fail() returns a true value. The program never manages to open the file. The file "users.txt" is in the same location as the program.

I'm using Dev-C++ on Windows xp.
Last edited on
I've had weird problems before with fstreams not liking to write after opening/closing one file for some reason...I don't remember exactly what the problem was though...you could try using a different fstream instead.
Nope that didn't change anything
Never mind...i'm an idiot. I forgot to change the file's "hidden" attribute before opening it haha
For a text file, binary is not only unnecessary, but is inadvertently causing you the issue.
Looking at ofstream's constructor gives us the answer:
explicit ofstream ( const char * filename, ios_base::openmode mode = ios_base::out );

The second argument is defaultly ios_base::out, a bit which says "allow output." The only real difference between ifstream and ofstream is the default value for the second argument. Since you have set the type to "only binary" (i.e., no input or output), which has no real meaning. If you really wanted binary, you should've done:
outFile.open("users.txt", ios::binary | ios::out);

Hope this helps.
I already fixed the issue...I just forgot to tell the program to make the program visible before trying to open it. the program couldn't find the file because it was hidden. Thanks for the input though, I appreciate it :)
Topic archived. No new replies allowed.