You are here:

C++/Fstream->Flush()

Advertisement


Question
I had a code problem earlier but I managed to fix it using flush().  Essentially, I have to convert a text file of numbers into binary, and then later read them in and print them to a screen.  I had the following code
//****
string out = "test2.bin";

ofstream output;
output.open(out.c_str(), ios::out | ios::binary);
if (output.is_open()) {
short width = 9;
short height = 8;
short tempw;
short temph;
output.write((char *) (&width), sizeof(short));
output.write((char *) (&height), sizeof(short));
output.flush();
ifstream log(out.c_str(), ios::in | ios::binary);
if (log.is_open()) {
log.read((char *) (&tempw), sizeof(short));
printf("Width = %d  ",tempw);
log.read((char *) (&temph), sizeof(short));
printf("Height = %d\n",temph);
log.close();
} else {
cout << "didn't open log\n";
}
} else {
cout << "didn't open output";
}
output.close();
//****

If I did not have the line output.flush() before opening the log file, the values would not come out correctly.  Why is this?
   Jed

Answer
Hello Jed, thank you for the question.

I am assuming that the the file stream was becoming corrupted and flush somehow forced the correct values out of it and into the file.

The problem is that you are casting a short int to a char*. The correct way to put that number into the file is to you either a character buffer, or a stream. I tend to favor ostringstreams over a call to sprintf(), so here is an example:

short width = 9, height = 8;
std::stringstream oss;
oss << width << ' ' << height;
output << oss.str();

That should achieve the effect you are looking for without having to call flush(). Let me know if it doesn't.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.