我试图使用fread()
从文件中读取二进制数据,但在读取之后,文件流的当前位置不知何故取决于我正在读取的文件.
我用不同的输入文件运行这段简单的代码:
#include <stdio.h>
int main(int argc, char** argv) {
FILE* in = fopen(argv[1], "r");
char buff[10];
fseek(in, 0, SEEK_SET);
fread(buff, sizeof(char), 10, in);
printf("Final position: %d\n", (int)ftell(in));
return 0;
}
控制台(我在Windows上运行,来自MinGW的g++.exe编译器):
$ ./p.exe test_data/test_elf
Final position: 692
$ ./p.exe test_data/test.cc
Final position: 11
$ ./p.exe example.txt
Final position: 9
我预计最后的位置是10,因为我们从0开始,读取了10个字节.我哪里错了?
Update个
以下是文件内容:
$ hexdump example.txt
0000000 3231 3433 3635 3837 3039 6261 6463 6665
0000010 6867 6a69 6c6b 6f6e 7170 7372 7574 7776
0000020 7978 207a 2320 2524 265e 282a e229 9684
0000030 253b 3f3a 282a 7b29 5b7d 0a5d
000003c
$ hexdump test_data/test.cc
0000000 0a0d 7361 286d 6e22 706f 2922 0d3b 610a
0000010 6d73 2228 756c 2069 3278 202c 7830 3031
0000020 2230 3b29 2020 2020 2020 2020 2020 2020
0000030 2020 2f2f 5320 2050 6573 2074 6f74 3120
... (more)
$ hexdump test_data/test_elf
0000000 457f 464c 0101 0001 0000 0000 0000 0000
0000010 0002 00f3 0001 0000 0074 0001 0034 0000
0000020 0334 0000 0000 0000 0034 0020 0002 0028
0000030 0008 0007 0001 0000 0000 0000 0000 0001
... (more)