00000000000000000000000000000111
(32位。我算了)
现在我写了这段代码:
int main()
{
FILE * f1;
f1 = fopen("file2", "rb");
int i = 0;
fread(&i, sizeof(int), 1, f1);
printf("%d", i);
fclose(f1);
return 0;
}
打印我808464432。 为什么?不应该打印7? 谢谢你的阅读。
答案 0 :(得分:3)
这不是二进制文件,它是一个文本文件,请尝试使用
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
int value;
char text[33];
char *endptr;
file = fopen("file2", "r");
if (file == NULL) /* check that the file was actually opened */
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);
/* check that the content of the file is not printable, i.e. not text */
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
是nul
字节,用于标记字符串的结尾。
答案 1 :(得分:1)
这是您可以写入和读取二进制文件的一种方法。在读取它们之前,你应该知道二进制文件和ASCII文件之间的区别。 请阅读https://stackoverflow.com/a/28301127/3095460一次,并使用您的代码了解您正在阅读的文件类型。
如果您在编辑器中打开文件并查看00000000000000000000000000000111
它并不意味着它是一个二进制文件,那么大多数编辑器只会将文件处理为ascii文本文件。您需要一个二进制编辑器来打开二进制文件并从中读取有意义的数据。
#include <stdio.h>
int main()
{
FILE *Read_fptr = NULL;
FILE *Write_fptr = NULL;
int data = 20;
size_t nElement = 1;
if ( (Write_fptr = fopen("data.bin", "wb")) != NULL ) {
if ( fwrite(data, nElement, sizeof data, Write_fptr) != sizeof data ) {
fprintf(stderr,"Error: Writing to file\n");
fclose(Write_fptr);
return -1;
}
} else {
fprintf(stderr,"Error: opening file for writing\n");
return -1;
}
fclose(Write_fptr);
data = 0;
if ( (Read_fptr = fopen("data.bin", "rb")) != NULL ) {
if ( fread(data, nElement, sizeof data, Read_fptr) != sizeof data) {
if( !feof(Read_fptr) ) {
fprintf(stderr,"Error: Reading from file\n");
fclose(Read_fptr);
return -1;
}
}
} else {
fprintf(stderr,"Error: opening file for reading\n");
return -1;
}
fclose(Read_fptr);
printf("%d\n",data);
return 0;
}