Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ofstream doesn't flush

Tags:

c++

ofstream

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?

like image 451
kinslayer_e Avatar asked Jun 24 '10 19:06

kinslayer_e


People also ask

Can ofstream fail?

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.

Does close flush C++?

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.

Does ofstream truncate?

It truncates by default.

What happens if you don't close Filestream?

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.


1 Answers

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.

like image 76
log0 Avatar answered Nov 13 '22 09:11

log0