c - Unexpected output when using fseek -


assuming have text file named hi.txt contains following string:

abcde12345

let run code:

int main() {   file *fp;   fp = fopen("hi.txt","r");   if(null == fp) { return 1; }   fseek(fp,-1, seek_end);   while (ftell(fp) > 0) {      printf("%c",fgetc(fp));      fseek(fp,-4, seek_cur);   }   fclose(fp);   return 0; } 

when ran code printed: 3ebcd

when tried guess print thought should 52d. can explain has happened here ?

it looks there non-printable end-of-line character @ end of file. that's gets printed first. position moved in turn 3, e, , b. @ point, re-positioning -3 fails, because location become -2. file cursor stays was, i.e. @ c gets printed next. following attempt @ repositioning fails too, d gets printed. next repositioning succeeds, terminating loop.

to detect situations when fseek ignored, check return value, this:

while (ftell(fp) > 0) {     printf("%c",fgetc(fp));     // successful calls of fseek return 0     if (fseek(fp,-4, seek_cur)) {         // exit loop if can't jump 4 positions         break;     } } 

Comments