I'm getting different behavior between fstream
vs. oftream
which I cannot explain.
When I use fstream
, nothing happens, i.e. no file is created:
int main()
{
std::fstream file("myfile.txt");
file << "some text" << std::endl;
return 0;
}
but when I change fstream
to oftream
, it works.
Why?
The second argument of fstream
CTOR is ios_base::openmode mode = ios_base::in | ios_base::out
which makes me think that the file is opened in read-write mode, right?
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.
Note that any open file is automatically closed when the fstream object is destroyed.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
ios_base::in
requires the file to exist.
If you provide only ios_base::out
, only then will the file be created if it doesn't exist.
+--------------------+-------------------------------+-------------------------------+
| openmode | Action if file already exists | Action if file does not exist |
+--------------------+-------------------------------+-------------------------------+
| in | Read from start | Failure to open |
+--------------------+-------------------------------+-------------------------------+
| out, out|trunc | Destroy contents | Create new |
+--------------------+-------------------------------+-------------------------------+
| app, out|app | Append to file | Create new |
+--------------------+-------------------------------+-------------------------------+
| out|in | Read from start | Error |
+--------------------+-------------------------------+-------------------------------+
| out|in|trunc | Destroy contents | Create new |
+--------------------+-------------------------------+-------------------------------+
| out|in|app, in|app | Write to end | Create new |
+--------------------+-------------------------------+-------------------------------+
PS:
Some basic error handling could also prove useful in understanding what's going on:
#include <iostream>
#include <fstream>
int main()
{
std::fstream file("triangle.txt");
if (!file) {
std::cerr << "file open failed: " << std::strerror(errno) << "\n";
return 1;
}
file << "Some text " << std::endl;
}
Output:
C:\temp> mytest.exe
file open failed: No such file or directory
C:\temp>
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