   Proper binary file IO (C++)
  Ok in class I was given this code to open a file for binary output.(I haven't bothered with the index file)void init_files( fstream& index, fstream& master ){master.open( "master.bin", ios::in );if( master.fail() ){master.clear();master.close();master.open( "master.bin", ios::out | ios::binary );master.seekp( 0 );}master.clear();master.close();master.open( "master.bin", ios::in | ios::out | ios::binary );}This is strange to me because when I write in ASCII I just call the open function and I'm good to go.I expected this to workvoid init_files( fstream& index, fstream& master ){master.open( "master.bin", ios::in | ios::out | ios::binary );}but it doesn't. Why doesn't this just open a binary file and if it's not there create one?   
  IIRC this is to do with the output, i.e. where should it write to.If the file exist and you want to append then specify std::ios_base::app.If you do not care if the file exists and you want to overwrite the data, then add std::ios_base::trunc to the flags and it will open it if it exists or create it if it does not.edit:Alternatively if may be due to C FILE open modes.for example is ios::out | ios::in the equivalent to "w+" or "r+"[Edited by - CmpDev on May 6, 2009 7:32:41 PM];  A file is only created if ios::in is not specified, because if ios::in is specified and the file doesn't exist, it doesn't make sense to offer to read from a blank file. Thus, opening the file with ios::in only is used as a test to see if it's already there.Of course, code like that is potentially subject to race conditions. :/ Consider using Boost's libraries for this instead (streams and filesystem, IIRC).   ;Quote:Original post by ZahlmanA file is only created if ios::in is not specified, because if ios::in is specified and the file doesn't exist, it doesn't make sense to offer to read from a blank file.That is not true if you add the trunc flag it will create the file.IMHO after a little thought my edit with reference to the C fopen states makes sense, although I can not see anything in the standard to suggest this is the case.