Risks of seeking in text mode
What you'll learn: Why using fseek with specific byte offsets can lead to unpredictable behavior when working with text files.
The "Map vs. Reality" Problem
When you open a file in text mode ("r" or "w"), C performs a little bit of magic behind the scenes called translation. On many systems, especially Windows, the way a "new line" is stored on your hard drive is different from how it appears in your C code.
Think of it like a GPS map versus the actual road. On your map (your C code), a new line is just one character: \n. But on the physical road (the disk), it might be two bytes: a "Carriage Return" and a "Line Feed" (\r\n). Because C hides this from you to make coding easier, the byte count you think you're at might not match the byte count where the file pointer actually sits.
The danger of arbitrary numbers
In binary mode, fseek is like a ruler; if you move 10 units, you move exactly 10 bytes. In text mode, fseek is more like a teleportation device that only works reliably if you have the exact coordinates provided by the file system itself.
If you try to manually calculate an offset—for example, "I want to skip 5 characters, so I'll seek to position 5"—you might land right in the middle of a two-byte newline sequence. This can cause the next fgetc or fgets call to return garbled data, trigger errors, or skip parts of your file entirely.
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w+"); // Text mode
fputs("Hello\nWorld", file);
// DANGER: Moving 6 bytes ahead manually.
// On some systems, '\n' is 2 bytes, so position 6
// might be the second half of the newline!
fseek(file, 6, SEEK_SET);
int ch = fgetc(file);
printf("Character at position 6: %c\n", ch);
fclose(file);
return 0;
}
How to seek safely
To avoid these risks in text mode, follow two golden rules:
- Use
ftell: Only seek to positions you have previously saved using theftellfunction. This ensures you are using a "coordinate" the system understands. - Stick to constants: It is always safe to seek to the very beginning (
SEEK_SETwith offset 0) or the very end (SEEK_ENDwith offset 0).
Anything else is like trying to guess the exact millimeter of a crack in the sidewalk while wearing a blindfold.
Key takeaway
In text mode, never manually calculate byte offsets for fseek; only use values returned by ftell or move to the start/end of the file.