Binary files

Hello! I'm trying to learn how to use binary files instead of text files (supposedly they will take up less space?) and I have the following small test program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main() {

	int i;
	double d;
	char c;
	ofstream bout;
	bout.open("bina.dat", ios::binary);
	for(i=0;i<10;i++) {
		d=i*0.5;
		bout.write((const char *) &d, 4);
	}
	bout.close();
	
	ifstream bin;
	bin.open("bina.dat", ios::binary);
	while(bin.read((char *) &d, 4)) cout << d << endl;
	bin.close();

	return 0;
}


But when I run it it prints out 4.5 ten times (a similar one just printing out i , i.e. 0,...,9 worked fine). Any idea what the problem is?

Also, is there a way to condense line 9 and 10 into one line, that is to make it faster by doing the calculation and printing it on one go?

Jorgen

EDIT: small mistake
Last edited on
Are you sure that sizeof(double) == 4?
Noooooooo that might be 16:)

Thanks!
It could be 16 but it is probably 8. Instead if guessing you can use sizeof(double) in the code.
Ha, I always thought it was 16. sizeof(double) is safer I guess but in the end I will use this in a code where speed is crucial, and that would be a tiny bit slower right? (for a lot and lot of repetitions)
No it would not be slower.
Ok. Is that because the compiler optimizes it so the program doesn't have to find the size of double every time, or something like that?
The value of sizeof(double) is known at compile time. It's not much of an optimization.
Ok. I have a lot to learn.. On a related note, any idea why the following doesn't work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void test(ofstream *bout) {
	int i;
	double d;
	for(i=0;i<10;i++) {
		d=i*0.5;
		*bout.write((const char *) &d, sizeof(double));
	}
	*bout.close();
	
	ifstream bin;
	bin.open("bina.dat", ios::binary);
	while(bin.read((char *) &d, sizeof(double))) cout << d << endl;
	bin.close();
}

int main() {

	ofstream bout;
	bout.open("bina.dat", ios::binary);
	test(&bout);


	return 0;
}


Somehow passing the ofstream to a function I get the error " Request for member 'write' in 'bout', which is of non-class type 'std::ofstream*' ." I don't understand why ofstream now can't be used like this.
*bout.write((const char *) &d, sizeof(double));
is evaluated as
*(bout.write((const char *) &d, sizeof(double)));
so you have to put parentheses around *bout to make it work.
(*bout).write((const char *) &d, sizeof(double));
or you can use the arrow syntax (usually more convenient)
bout->write((const char *) &d, sizeof(double));
Last edited on
That worked, thanks a lot!
Topic archived. No new replies allowed.