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;

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?

9 Years
Discussion Span
Last Post by Ancient Dragon

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);

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.