fstream in and out on nonexistent file

Thomas picture Thomas · May 24, 2010 · Viewed 14.2k times · Source

Is it possible to open an fstream on a file that does not exist with both ios::in & ios::out without getting an error?

Answer

Johnsyweb picture Johnsyweb · May 24, 2010

To open an fstream on a file that does not exist for input and output (random access) without getting an error, you should provide the flags fstream::in | fstream::out | fstream::trunc in the open (or constructor) call. Since the file does not already exist, truncating the file at zero bytes is no drama.

You may want an error when opening a file that doesn't exist when specifying only ios::in since you'll never be able to read from the stream so failing early in this case will prevent surprise failures later on.