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>