fread 不是从文件的开头开始
fread is not starting at the beginning of the file
我正在从事一个涉及将二进制数据从文件读取到特定数据结构的项目。在测试时,我看到不正确的数据被加载到这些结构中。添加一点调试代码(使用 ftell
)显示 fread
不是从文件的开头开始,而是在数百字节深的某个偏移处。可能是什么原因造成的?
我尝试在第一个 fread
调用之前添加 fseek(infile, 0, SEEK_SET);
,但第一个调用仍然以与之前相同的偏移量开始。我也尝试使用 rewind(infile)
无济于事。我确实看到是否发生此问题取决于正在读取的文件。有些文件总是从位置 0 开始,而其他文件总是从其他偏移量开始。
这是在我的机器上出现此问题的最小代码示例。我目前是 运行 Windows 10 并且代码是在 Visual Studio.
中编译的
#include <stdio.h>
int main(int argc, char* argv[]) {
FILE* infile;
char* inname;
char x;
inname = argv[1];
if ( (fopen_s(&infile, inname, "r")) != 0) {
printf("Error opening file: %s\n", inname);
exit(1);
}
if (infile == 0) {
printf("Error opening file.\n");
exit(1);
}
while (fread(&x, sizeof(char), 1, infile) == 1) {
printf("%ld\n", ftell(infile));
printf("%hhx\n\n", x);
}
fclose(infile);
return 0;
}
您应该以二进制读取模式打开文件。
if ( (fopen_s(&infile, inname, "r")) != 0) {
到
if ( (fopen_s(&infile, inname, "rb")) != 0) {
The mode string can also include the letter 'b' either as a last
character or as a character between the characters in any of the
two-character strings described above. This is strictly for
compatibility with C89 and has no effect; the 'b' is ignored on all
POSIX conforming systems, including Linux. (Other systems may treat
text files and binary files differently, and adding the 'b' may be a
good idea if you do I/O to a binary file and expect that your program
may be ported to non-UNIX environments.)
我正在从事一个涉及将二进制数据从文件读取到特定数据结构的项目。在测试时,我看到不正确的数据被加载到这些结构中。添加一点调试代码(使用 ftell
)显示 fread
不是从文件的开头开始,而是在数百字节深的某个偏移处。可能是什么原因造成的?
我尝试在第一个 fread
调用之前添加 fseek(infile, 0, SEEK_SET);
,但第一个调用仍然以与之前相同的偏移量开始。我也尝试使用 rewind(infile)
无济于事。我确实看到是否发生此问题取决于正在读取的文件。有些文件总是从位置 0 开始,而其他文件总是从其他偏移量开始。
这是在我的机器上出现此问题的最小代码示例。我目前是 运行 Windows 10 并且代码是在 Visual Studio.
中编译的#include <stdio.h>
int main(int argc, char* argv[]) {
FILE* infile;
char* inname;
char x;
inname = argv[1];
if ( (fopen_s(&infile, inname, "r")) != 0) {
printf("Error opening file: %s\n", inname);
exit(1);
}
if (infile == 0) {
printf("Error opening file.\n");
exit(1);
}
while (fread(&x, sizeof(char), 1, infile) == 1) {
printf("%ld\n", ftell(infile));
printf("%hhx\n\n", x);
}
fclose(infile);
return 0;
}
您应该以二进制读取模式打开文件。
if ( (fopen_s(&infile, inname, "r")) != 0) {
到
if ( (fopen_s(&infile, inname, "rb")) != 0) {
The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-UNIX environments.)