-2

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);
  }
}
daljinder singh
  • 177
  • 1
  • 9
  • 3
    1.) see [why while( !feof() ) is always wrong](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Ingo Leonhardt Apr 26 '17 at 15:47
  • 1
    2.) you don't reassign `fp` with your second `fopen( "RANDON", "r" )` – Ingo Leonhardt Apr 26 '17 at 15:48
  • 1
    You are using `feof()` and `ftell()` then you are even reading from a closed file. You probably wanted to `fp = fopen("RANDOM", "r");`. – axiac Apr 26 '17 at 15:51
  • Exactly. This invokes *undefined behavior*. You closed the `fp`, opened the file again and leaked the resulting result (likely a valid `FILE*`) never to be seen again, then sent the old, still closed, `fp` in to your loop. Short version: you're missing `fp = ` in this code. – WhozCraig Apr 26 '17 at 15:51
  • actually that was a copy mistake, it is still not working with the `fp =` added. – daljinder singh Apr 26 '17 at 15:58
  • 1
    What are you trying to accomplish using `c = getchar()) != EOF` ? – sjsam Apr 26 '17 at 16:03
  • it will take input from the user until the user presses `ctrl-d` which assign EOF meaning end of the file. – daljinder singh Apr 26 '17 at 16:05

1 Answers1

3

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);
}
Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
  • Please don't repeat the error of using the magic number `1` as the third argument to `fseek()`. The only proper values are `SEEK_SET`, `SEEK_CUR`, and `SEEK_END`. – Andrew Henle Apr 26 '17 at 16:24