Reputation: 1177
I'm trying to write 4 unsigned short int
numbers represented in hex into a binary file.
I keep getting a lot of junk in addition to the numbers I'm writing, and I'm not sure why. I'm assuming that in the translation from unsigned short int
to binary, there's junk being written into my file.
My function to write into my binary file is:
int write_file (char* name, unsigned short int array[x] ){
FILE *fptr;
fptr = fopen(name, "wb");
if(fptr==NULL)
{
fclose(fptr);
return (0);
}
unsigned short int code = 0xABCD;
const void *ptr = &code;
fwrite(ptr, sizeof(ptr), 1, fptr);
unsigned short int code2 = 0x0000;
const void *ptr2 = &code2;
fwrite(ptr2, sizeof(ptr2), 1, fptr);
unsigned short int code3 = 0x0001;
const void *ptr3 = &code3;
fwrite(ptr3, sizeof(ptr3), 1, fptr);
unsigned short int code4 = 0x1101;
const void *ptr4 = &code4;
fwrite(ptr4, sizeof(ptr4), 1, fptr);
return (0);
}
Ideally the binary file would be interpreted as:
ABCD 0000 0001 1101
But I'm getting this instead:
abcd f250 0190 0000 0000 eeb6 1915 7ffd
0001 eea6 1915 7ffd 1101 ee96 1915 7ffd
Upvotes: 0
Views: 1626
Reputation: 595392
fwrite()
.You are passing the byte size of each void*
variable. sizeof(void*)
is 4 bytes in a 32bit build, and 8 bytes in a 64bit build (sizeof(void*)
would appear to be returning 8 in your case). You need to instead pass the byte size of the unsigned short int
variables (2 bytes) that are being pointed at.
You don't need the void*
variables at all. And don't forget error checking:
int write_obj_file (char* filename, unsigned short int program_bin[ROWS] ){
FILE *fptr = fopen(filename, "wb");
if (fptr == NULL)
return -1;
unsigned short int code = 0xABCD;
if (fwrite(&code, sizeof(code), 1, fptr) < 1) {
fclose(fptr);
return -1;
}
unsigned short int code2 = 0x0000;
if (fwrite(&code2, sizeof(code2), 1, fptr) {
fclose(fptr);
return -1;
}
unsigned short int code3 = 0x0001;
if (fwrite(&code3, sizeof(code3), 1, fptr) {
fclose(fptr);
return -1;
}
unsigned short int code4 = 0x1101;
if (fwrite(&code4, sizeof(code4), 1, fptr) {
fclose(fptr);
return -1;
}
fclose(fptr);
return 0;
}
Upvotes: 5