Search code examples
cfseek

fseek() crossing file limit and not terminating


In the last while loop, every 5th character stored in the file should be printed, but the loop is going on indefinitely and not terminating. the feof() function should return 1 on reaching END OF FILE and the loop should be exited but the loop is going on indefinitely.

#include<stdio.h>

main() {
  long n, k;
  char c;
  FILE *fp;
  fp = fopen("RANDOM", "w");

  while ((c = getchar()) != EOF) {
    putc(c, fp);
  }

  n = ftell(fp);
  printf("\nNo. of characters entered by the user is : %ld\n", n);
  fclose(fp);
  fp = fopen("RANDOM", "r");

  while(feof(fp) == 0) {
    n = ftell(fp);
    c = getc(fp);
    printf("The character at %ld position is %c\n", n, c);
    fseek(fp, 4l, 1);
  }
}

Solution

  • From man fseek():

    A successful call to the fseek() function clears the end-of-file indicator for the stream.

    And fseek() will be successful even when you set the position indicator behind EOF. So it becomes clear that while (feof(fp) == 0) will never terminate when fseek() is the last command within the loop.

    Instead, you could do:

    for( ;; ) {
        n = ftell(fp);
        if( (c = getc(fp)) == EOF )
             break;
        printf("The character at %ld position is %c\n", n, c);
        fseek(fp, 4l, SEEK_CUR);
    }