[英]writing binary to a file using unsigned short in C with fwrite()
I'm trying to write 4 unsigned short int
numbers represented in hex into a binary file.我正在尝试将 4 个以十六进制表示的
unsigned short int
写入二进制文件。
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.我假设在从
unsigned short int
到二进制的翻译中,有垃圾被写入我的文件中。
My function to write into my binary file is:我的 function 写入我的二进制文件是:
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
fwrite()
.fwrite()
。 You are passing the byte size of each void*
variable.您正在传递每个
void*
变量的字节大小。 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). sizeof(void*)
在 32 位构建中为 4 个字节,在 64 位构建中为 8 个字节(在您的情况下sizeof(void*)
似乎返回 8)。 You need to instead pass the byte size of the unsigned short int
variables (2 bytes) that are being pointed at.您需要传递指向的
unsigned short int
变量(2 个字节)的字节大小。
You don't need the void*
variables at all.您根本不需要
void*
变量。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.