Is it possible to open an fstream on a file that does not exist with both ios::in & ios::out without getting an error?
The best way to check if a file exists using standard C/C++ The only way to check if a file exist is to try to open the file for reading or writing.
In this case, nothing will happen and code execution time is very less. However, if your codes runs for long time when you are continuously opening files and not closing, after a certain time, there may be crash in run time.
fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient. In particular, it's not a “best practice” and it's not necessary to flush the output.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With