那不是二进制文件,而是文本文件,请尝试使用以下方法。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
int value;
char text[33];
char *endptr;
file = fopen("file2", "r");
if (file == NULL)
return -1;
if (fread(text, 1, sizeof(text) - 1, f1) != sizeof(text) - 1)
{
fclose(file);
return -1;
}
text[32] = '\0';
value = strtol(text, &endptr, 2);
if (*endptr == '\0')
printf("%d", value);
fclose(file);
return 0;
}
要写入二进制文件,你需要使用以下代码:
#include <stdio.h>
void hexdump(const char *const filename)
{
FILE *file;
unsigned char byte;
file = fopen(filename, "rb");
if (file == NULL)
return;
fprintf(stdout, "hexdump of `%s': ", filename);
while (fread(&byte, 1, 1, file) == 1)
fprintf(stdout, "0x%02x ", byte);
fprintf(stdout, "\n");
}
int main()
{
const char *filename;
FILE *file;
int value;
filename = "file.bin";
file = fopen(filename, "wb");
if (file == NULL)
return -1;
value = 7;
if (fwrite(&value, sizeof(value), 1, file) != 1)
fprintf(stderr, "error writing to binary file\n");
fclose(file);
hexdump(filename);
file = fopen(filename, "rb");
if (file == NULL)
return -1;
value = 0;
if (fread(&value, sizeof(value), 1, file) != 1)
fprintf(stderr, "error writing to binary file\n");
else
fprintf(stdout, "The value read was %d\n", value);
fclose(file);
return 0;
}
如上面的示例所示,在file.bin
中存储的数据不是文本格式,您无法使用文本编辑器检查它,因为字节0x00
和0x07
是不可打印的,事实上,0x00
是在C语言中用于标记字符串结尾的nul
字节。
sizeof(int)
。你可能正在处理 2 字节的 int,这意味着你读取了两个字节的 0 位值,这意味着你的“int”将为0
。而你是如何计算这些位的呢?如果您的文件是“二进制”的,则它的文件大小为 4 字节。如果是文本,则为 32 字节。 - Marc Bfwrite(&i, sizeof i, 1, f1)
- mafso