2

i make this simple C program whose purpose is to count the characters that are in a text file which is given through the second command line argument. The problem i face is that fseek shows not responds with a result to have an infinite loop (while(!feof(fp))) in function "Counter".By replacing the fseek with a fgetc the programm works fine.My my question is what is going wrong with the fseek. Thanks in advance.

#include <stdio.h>

int Counter (FILE * fp);

int main(int argc, char* argv[])
{
   int cntr;
   FILE * fpc;
   fpc = fopen(argv[1],"r");
   cntr = Counter(fpc);
   fclose(fpc);
   printf("%i\n",cntr);
}

int Counter (FILE * fp)
{
    int cntr = 0;
    while (!feof(fp))
    {
        cntr++;
        fseek(fp,1,1);
    }
    return cntr;
}
Spyreto
  • 29
  • 5

1 Answers1

3

It is allowed and well defined behaviour to seek beyond the end of a file.

That's why fseek() does not set the end-of-file indicator, it even more unsets it on success.

From the C Standard:

5 After determining the new position, a successful call to the fseek function [...] clears the end-of-file indicator for the stream, and then establishes the new position.

alk
  • 69,737
  • 10
  • 105
  • 255
  • 1
    Good catch! I have seen code where you can write a byte, `fseek` 1 GB further and write another byte, leading to the file system seeing a 1 GB file fitting on a 256 MB disk. – Matthieu Apr 30 '16 at 16:33