I have this strange bug. I have a program which writes text to the file using the fstream, but the file is not being created and therefore no text is appended. When I debug my code, it shows me this:
create_new_file = {_Filebuffer={_Pcvt=0x0000000000000000 <NULL> _Mychar=0 '\0' _Wrotesome=false ...} }.
But whenever I use ofstream everything works.
Here is the code:
std::fstream create_new_file{ fileName.str()};
std::unique_ptr<std::string> changes = std::make_unique<std::string>("");
std::cin >> *changes;
create_new_file << *changes << "\n";
Here is the code which works:
std::ofstream create_new_file{ fileName.str()};
I have seen a similar post on Stack Overflow but the answer did not resolve my issue. I have tried adding the std::ios::trunc to the fstream but that did not help. But whenever I use ofstream everything works just as expected.
CodePudding user response:
The problem is that for bidirectional file streams the trunc
flag must always be explicitly specified, i.e., if you want the file content to be discarded then you must write in | out | trunc
as the second argument as shown below.
Thus, to solve the problem change std::fstream create_new_file{ fileName.str()};
to :
//-------------------------------------------------------------------------vvvvvvvvvvvvvvv---->explicitly use trunc
std::fstream create_new_file{ "output.txt", ios_base::in | ios_base::out | ios_base::trunc};
CodePudding user response:
This file stream buffer open
reference is useful. It shows a table with the different modes and what happens when they are used.
When you open a std::fstream
the default mode for the constructor is in | out
. If we look that up in the table we see that this will fail if the file doesn't exist.
And you never check for failure (which you always should do).
If you only want to write to the file then use std::ofstream
as it will open the files in out
mode, which creates the file if it doesn't exist.
If you want to only append to the file, still use std::ofstream
but use the mode out | app
, which will create the file and make sure all output is appended (written to the end).