TITLE: file I/O using streams (Newsgroups: comp.std.c++, 8 May 97) ROHEAD: Sean Rohead > > Is there a standard way to open a file for reading and writing if the file > does not currently exist? > > fstream::open(filename,ios::in | ios::out) will fail if the file isn't > there already. Isn't there some way to force the file to be created? A > quick glance at the standard didn't yield any insights. CLAMAGE: Steve Clamage Original iostreams did not specify exactly how opening for read/write should work. Consequently, current implementations vary. The draft standard now defines all operations in terms of stdio operations. You have only three options in opening a stdio file for read/write: "r+": file must already exist "w+": file will be truncated to zero length if it exists "a+": all writes will be forced to the end of the file Append "b" to the string for binary mode. The corresponding fstream flags are: in|out: same as "r+" in|out|trunc: same as "w+" Add the "binary" flag for binary mode. I think the draft should also specify in|out|app to correspond to "a+" but it currently does not allow that combination. I believe that combination was accidently left out, and I will investigate. Perhaps you want in|out|trunc correspoding to "w+". You can read and write the file at arbitrary points, and the file need not already exist. It will be truncated to zero length if it does exist. If you want to open a file for arbitrary read/write, preserving the existing contents, creating the file if it does not already exist, you cannot do it in one operation. You could do something like this: fstream f("filename", ios::in|ios::out|ios::binary); if( ! f.is_open() ) f.open("filename", ios::in|ios::out|ios::binary|ios::trunc); In other words, if the "r+" open fails, open it as "w+", which will create an empty file.