2

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?

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Steve
  • 4,859
  • 5
  • 21
  • 17

2 Answers2

8

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.

  • 2
    As noted in the C standard: "The values stored [by fgetpos()] contain unspecified information usable by the fsetpos function for repositioning the stream to its position at the time of the call to the fgetpos function." – Michael Burr Aug 14 '09 at 17:49
1

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
  • 8,757
  • 2
  • 32
  • 36