Fopen_s, Fread, Fseek

Just get bitten by a problem. I read file using the following code under Windows

FILE *pFile;
char o_buf[100];
long offset = 0;
size_t bytesRead = 0;

fopen_s(&pFile, “myfile.txt”, “a+”);
fseek(pFile, offset, SEEK_SET);
bytesRead = fread(o_buf, 1, 100, pFile);

offset += bytesRead;
fseek(pFile, offset, SEEK_SET);
bytesRead = fread(o_buf, 1, 100, pFile);

What I have found is the o_buf got in the second time overlaps with o_buf got in the first time. It seems like the bytesRead doesn’t move enough to the expected position. Finally, I figure out it’s because the file contains newline character represented by 0x0d 0x0a. And because I am NOTopening it in binary mode, the fread automatically converts 0x0d 0x0a to 0x0d when reading it to memory. In another word, when the file reads a newline character, its internal file position is moving forward by 2 bytes while the bytesRead reported by API is only 1. Of course, if I don’t use fseek the second time and just call fread, I won’t have the issue. As an another way to fix the problem, simply use

fopen_s(&pFile, “myfile.txt”, “a+b”);

Pretty basic but a good lesson anyway.

Subscribe to 天舟的云游格

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe