I'm trying to use fstreams to read and write binary data to a file with the following code:

#include <fstream>
#include <iostream>
using namespace std;

int main(){
	ofstream out("test.data", ios::binary);
	for(uint i=0; i<10; i++){
		uint outcount = i+100;
		out.write((char*)&outcount, sizeof(uint));
	}
	ifstream in("test.data", ios::binary);
	for(int i=0; i<10; i++){
		uint incount;
		in.read((char*)&incount, sizeof(uint));
		cout << i << " " << incount << endl;
	}
	out.close();
	in.close();
}

However it isn't working for me; it just keeps outputting "10" instead of 100, 101, etc. as I would expect.

What's my mistake?

Recommended Answers

All 4 Replies

You need to close the output file before opening the input file because some of the data has not been flushed to disk yet.

Yes that worked, thanks :)

Another question: what is the purpose of the ios::binary flag? When I try it, the output and input is always binary, even if the flag is omitted and other flags like ios::app are used instead.

The binary flag prevents streams from interpreting any of the binary characters (whose character values outside the range of normal printable characters). In normal text files the "\r\n" characters (ms-windows) in the file are used to indicate end-of-line for functions such as getline(). Binary files may also by coincidence have the "\r\n" pair, so the binary flag is used to prevent any interpretion by fstream.

>>and other flags like ios::app are used instead
You can use both flags at the same time by using the or operator | to combine them ofstream out("test.data", ios::binary | ios::app);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.