I have the following code, running on Suse 10.1 / G++ 4.1.0, and it doesn't write to the file:
#include <fstream>
#include <iostream>
int main(){
std::ofstream file("file.out");
file << "Hello world";
}
The file is correctly created and opened, but is empty. If I change the code to:
#include <fstream>
#include <iostream>
int main(){
std::ofstream file("file.out");
file << "Hello world\n";
}
(add a \n
to the text), it works.
I also tried flushing the ofstream, but it didn't work.
Any suggestions?
To get ofstream::open to fail, you need to arrange for it to be impossible to create the named file. The easiest way to do this is to create a directory of the exact same name before running the program.
NOTE: close() is typically called through the destructor of std::basic_filebuf (which, in turn, is typically called by the destructor of std::basic_fstream . First of all, we can see that it doesn't actually call flush() directly as you expected.
It truncates by default.
Similar thing should happen in case of all operating system. It won't prevent the whole system from running, the application will just fail to open more files. It might prevent your whole application from running.
If you check your file doing a cat
, it may be your shell that is wrongly configured and does not print the line if there is no end of line.std::endl
adds a \n
and flush.
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