Binary read and write

Oct 24, 2016 at 5:52pm
Hello I have a problem: I have a file data.dat, which i want to read in and then print out on console. here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main() {

	ifstream file("data.dat");

	char *buffer = new char[128];
	file.read(buffer, 128);

	bitset<8> t(buffer[0]);
	cout << t << endl;
	bitset<8> z(buffer[1]);
	cout << z << endl;
	return 0;
}



so and data.dat starts with 0110101110001011010001010110011100110...

but my output is :

00001100
00100100


thats not the same like the first 16 bits of my file.

what went wrong? what do i have to change to get sure, the output will be the same like the data.dat??

thank u very much
Last edited on Oct 24, 2016 at 5:53pm
Oct 24, 2016 at 6:28pm
1. Open the file in binary mode
 
    ifstream file("data.dat", std::ios::binary);


2. Next, check that the file was actually opened successfully
1
2
3
4
5
    if (!file)
    {
        cout << "file not open\n";
        return 1;
    }


3. When reading the file, check that the read operation was successful, possibly like this:
1
2
3
4
5
    if (!file.read(buffer, 128))
    {
        cout << "file read error\n";
        return 2;
    }



edit
If the read failed, you may want to use the gcount() function to find how many bytes were actually read from the file. See example:
http://www.cplusplus.com/reference/istream/istream/read/

Last edited on Oct 24, 2016 at 7:15pm
Oct 25, 2016 at 10:47am
Nice it really worked, thank u very much!
Topic archived. No new replies allowed.