Narek Narek - 3 months ago 7
C++ Question

Why doesn't std::fstream write to a file?

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?

Answer

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>