You are here:



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;, 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));
ifstream log(out.c_str(), ios::in | ios::binary);
if (log.is_open()) { *) (&tempw), sizeof(short));
printf("Width = %d  ",tempw); *) (&temph), sizeof(short));
printf("Height = %d\n",temph);
} else {
cout << "didn't open log\n";
} else {
cout << "didn't open output";

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

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


All Answers

Answers by Expert:

Ask Experts




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 I also know a good deal about graphics via OpenGL, and GUIs.


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.

©2017 All rights reserved.