Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ofstream out("f.bin");
	char c = 0x61;
	out.write(&c, sizeof(char));

	ifstream in("f.bin");
	char d;
	in.read(&d, sizeof(char));
	if (d != 0x61) cerr << "Extraction failed!" << endl; //this always appears

	return 0;
}


This is a simplified snippet of my attempt in a practice of dealing with binary file i/o. The hex editor shows that writing is successful ('a' in f.bin), but I have no idea why I cannot extract the char from the file (). What did I miss here?
Posted
Comments
PIEBALDconsult 15-Jun-15 22:30pm    
Dunno. Maybe the buffer didn't get flushed? Can you type the file to the console and see the character?

1 solution

Try:

C++
int main()
{
	ofstream out("test.bin", ofstream::out);

	char c = 0x61;
	out.write(&c, sizeof(char));

	out.close();
 
	ifstream in("test.bin", ofstream::in);
	char d;
	in.read(&d, sizeof(char));
	if (d != 0x61) cerr << "Extraction failed!" << endl; //this always appears
	in.close();

	return 0;
}


http://www.cplusplus.com/doc/tutorial/files/[^]
 
Share this answer
 
v2
Comments
Member 11212276 15-Jun-15 23:11pm    
Hmm since ofstream::out and ifstream::in are default mode, it's close that does the trick? So it's really buffer related issue? But I'm still confused how are buffers for ofstream and ifstream related? Do you mind explaining it to me as if to a dummy?:s
[no name] 15-Jun-15 23:19pm    
Data is not written until the close(). Flush() should also work but close() is guaranteed. The link I added should explain it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900