Question

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?

Was it helpful?

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.

OTHER TIPS

It's a Windows thing. In text mode Windows expands '\n' to 'CR''LF' on writes, and compresses 'CR''LF' to '\n' on reads. Text mode is the default mode on windows. As Neil mentions, adding 'b' into the mode string of fopen() turns off newline translations. You won't have this translation on *nix systems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top