What's wrong with this code? Each time I run it, it gives a different (wrong) output. Makes no difference whether I use put() or <<.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int intval1 = 1919006563; // this is what I should get back
int intval2, intval3;
ofstream fout( "eof.dat", ios::binary );
if( fout == NULL ) {
cout << "couldn't open for output\n";
return 1;
}
// fout.put( 99 ); //01100011
// fout.put( 183 ); //10110111
// fout.put( 97 ); //01100001
// fout.put( 114 ); //01110010
fout << (unsigned char)99;
fout << (unsigned char)183;
fout << (unsigned char)97;
fout << (unsigned char)114;
fout << intval1;
fout.close();
ifstream fin( "eof.dat", ios::binary );
if( fin == NULL ) {
cout << "couldn't open for input\n";
return 1;
}
fin >> intval2 >> intval3;
cout << "intval2 = " << intval2 << ", intval3 = " << intval3 << endl;
fin.close();
return 0;
}
On the other hand, using C i/o functions it behaves nicely:
Code:
#include <cstdio>
int main () {
int intval1, intval2, intval3;
unsigned char charr[4];
intval1 = 1919006563; // this is what I should get back
void* vp;
vp = &intval1;
FILE* iofile;
iofile = fopen( "test.dat", "wb" );
if( iofile == NULL ) {
printf("couldn't open for output\n");
return 1;
}
fputc( 99, iofile );
fputc( 183, iofile );
fputc( 97, iofile );
fputc( 114, iofile );
fwrite( vp, 4, 1, iofile );
fclose( iofile );
iofile = fopen( "test.dat", "rb" );
if( iofile == NULL ) {
printf("couldn't open for input\n");
return 1;
}
vp = &intval2;
fread( vp, 4, 1, iofile );
printf( "intval2 = %d\n", intval2);
vp = charr;
fread( vp, 1, 4, iofile );
printf("chars = %d, %d, %d, %d\n", charr[0], charr[1], charr[2], charr[3]);
fclose( iofile );
return 0;
}
Is there any way to do this using C++ iostreams?
Edit: It is not a mistake that I am swapping the uchars and the ints. I was intentionally trying to write 4 uchars and read back an int, and vice versa.