ofstream doesn't flush

kinslayer_e picture kinslayer_e · Jun 24, 2010 · Viewed 15.6k times · Source

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?

Answer

log0 picture log0 · Jun 24, 2010

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.