C++/Fstream->Flush()
Expert: Eddie - 8/9/2006
QuestionI 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
AnswerHello 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