I'm trying to read binary data from file using fread()
, but after reading, current position of filestream somehow depends on file I am reading.
I run this simple code with different input files:
#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;
}
Console (I run it on Windows, g++.exe compiler from MinGW):
$ ./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
I expect the final position to be 10, because we started on 0 and read 10 bytes. Where am I wrong?
Update
Here is file contents:
$ 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)
@mozhayaka I think, you might as well use "rb"
mode instead of "r"
. When you open a file in text mode "r"
, on some systems, newline characters '\n'
in the file are automatically translated to the appropriate new line sequence for that system.
So change your fopen
line to:
FILE* in = fopen(argv[1], "rb");
Hope to be helpful.