The flow does not merge

I have the following code running on Suse 10.1 / g ++ 4.1.0 and it does not write to the file:

#include <fstream> #include <iostream> int main(){ std::ofstream file("file.out"); file << "Hello world"; } 

The file is correctly created and open, but empty. If I changed the code to:

 #include <fstream> #include <iostream> int main(){ std::ofstream file("file.out"); file << "Hello world\n"; } 

(add text \n to text), it works. I also tried flushing the stream, but it did not work.

Any suggestions?

+7
c ++ ofstream
source share
4 answers

If you check your file with cat , it could be your shell, which is incorrectly configured and does not print a line if there is no end of line.
std::endl adds flash \n and .

+7
source share

I don't know if this was what you tried, but you have to do:

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

Update; I am leaving this answer here due to helpful comments

Based on the feedback, I will change my advice: you do not need to explicitly call std::flush (or file.close() , for that matter), because the destructor does this for you.

In addition, a call to flush explicitly forces an I / O operation, which may not be the most optimal. It will be better to correspond with the basic iostreams and the operating system.

Obviously, the OP problem is not related to calling or not calling std::flush , and probably due to trying to read the file before the file stream destructor was called.

+4
source share

The destructor must hide and close the file.

I'm sure the mistake is another place, either

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

2) Somehow the program crashes before it crashes?

+4
source share

whether

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

Job?

endl inserts a new line and flushes the buffer. Is that what you talked about when you said you already tried to rinse it?

0
source share

All Articles