C++ – fstream in and out on nonexistent file

cfstream

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

Best Answer

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.