OK, here is a problem that I have found described many times on the net, but have not found a definitive solution. Until recently, file writing has worked just fine for me, but no longer.
The questions are:
Why does it not work now?
What might I have done somewhere else in the code to break it?
How do I fix it?
My full code is over 10,000 lines long, so I really cannot provide it all here. But here is the issue:
string logfilename="Log/test.err"; fstream filename; filename.open(logfilename.c_str(),fstream::app); filename << "Start Log\n"; filename << std::flush; filename.close();
This code creates the file test.err in the Log folder (if it was missing, it will also create a missing Log folder). But the file remains empty. It fails to write "Start Log" into the file.
However. . .
string logfilename="Log/test.err"; fstream filename; filename.open("Log/test.err",fstream::app); filename << "Start Log\n"; filename << std::flush; filename.close();
This works just fine. Notice that the only difference is that I replaced the variable logfilename with its contents. Since fstream.open really wants a char, I tried this. . .
char *nn =(char*)logfilename.c_str(); fstream filename; filename.open(nn, fstream::app); filename << "Start Log\n"; filename << std::flush; filename.close();
This code works just like the first code. It creates the file if it was missing, but fails to write anything into it.
I have tried these three versions with filename.open(nn, fstream::out) with no change in the outcome (although in this application I really want a function that appends data to the file). I have also tried this without the "Log/" in the file name, so that the file would be in the active folder. Still no difference in outcome. I have also tried this with the target file already made (but empty). Still nothing is written to the file.
I have #include <fstream> at the start of each program (wouldn't really compile without that).
I am using MinGW to compile this as a C++ program. No error messages and no warnings occur during compilation.
I've read the fstream tutorials (on this site and others) and as far as I can tell I am following the directions.
So, what's going on?