Spyreto
Spyreto

Reputation: 29

Fseek doesn't sets the file position of the stream in C

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;
}

Upvotes: 2

Views: 864

Answers (1)

alk
alk

Reputation: 70931

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.

Upvotes: 3

Related Questions