Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

The destructor should flush and close the file.

I am pretty sure, the error is an another place, either

1) You do not check at the right point in time. At which point do you compare the content of the file, "after" the exits, or do you set a breakpoint before the program exits and then you check the files content?

2) Somehow the program crashes before it exits?

Don't know if this is what you tried but you should do:

file << "Hello World" << std::flush;

Update; I'm leaving this answer here because of the useful comments

Based on feedback, I'll modify my advice: you shouldn't have to explicitly call std::flush (or file.close() for that matter), because the destructor does it for you.

Additionally, calling flush explicitly forces an I/O operation that may not be the most optimized way. Deferring to the underlying iostreams and operating system would be better.

Obviously the OP's issue was not related to calling or not calling std::flush, and was probably due to attempting to read the file before the file stream destructor was called.

Does

file << "Hello world" << std::endl;

work?

endl inserts a newline and flushes the buffer. Is that what you were referring to when you said that you'd already tried flushing it?

You are working on Linux, which is a POSIX-compliant system. The POSIX standard defines what a line is:

A sequence of zero or more non-newline characters plus a terminating newline character.

So without the newline character, the file contains 0 lines and is therefore empty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top