c++freadfgetpos

c++ fread changing fgetpos strangely


If I run:

FILE* pFile = fopen("c:\\08.bin", "r");
fpos_t pos;
char buf[5000];

int ret = fread(&buf, 1, 9, pFile);
fgetpos(pFile, &pos);

I get ret = 9 and pos = 9.

However if I run

FILE* pFile = fopen("c:\\08.bin", "r");
fpos_t pos;
char buf[5000];

int ret = fread(&buf, 1, 10, pFile);
fgetpos(pFile, &pos);

ret = 10 as expected, but pos = 11!

How can this be?


Solution

  • You need to open the file in binary mode:

    FILE * pFile = fopen("c:\\08.bin", "rb"); 
    

    The difference is cause by reading a character that the library thinks is a newline and expanding it - binary mode prevents the expansion.