Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fstream in and out on nonexistent file

Tags:

c++

fstream

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

like image 550
Thomas Avatar asked May 24 '10 10:05

Thomas


People also ask

How do I check if a file exists in C++?

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.

What happens if you don't close Filestream?

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.

Do I need to close fstream?

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.


1 Answers

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.

like image 143
Johnsyweb Avatar answered Sep 28 '22 02:09

Johnsyweb