tags:

views:

207

answers:

3

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?

+6  A: 

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.

anon
As noted in the C standard: "The values stored [by fgetpos()] contain unspecified information usable by the fsetpos function forrepositioning the stream to its position at the time of the call to the fgetpos function."
Michael Burr
As fine an example of standardese as I've ever read!
anon
+1  A: 

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.

Rob K
A: 

oh that explains it! thanks for the help!

concerned