Search code examples
cfile-iofseek

How to get the character at the current position using C program?


I am trying to write a C program to get the character in the file which is ofset by some bytes, lets say three as below

fseek(fp,3,SEEK_CUR);

I wish to print the character which that particular byte represents. For example if my file contains something like below,I need to print every third character.

//reading from file//

The problem is that after using a while loop I am not able to print the desired result. The first character which gets printed is the fourth character instead of third.

while(fp!=EOF)
{
    fseek(fp,3,SEEK_CUR);
    ch = fgetc (fp);
    printf("%c",ch);
}

Can you please help me in understanding what is the mistake with this. Thanks!


Solution

  • fgetc moves the file offset by one. Try the following:

    fseek(fp,3,SEEK_CUR);
    while(fp!=EOF)
    {
        ch = fgetc (fp); // moves offset by 1
        fseek(fp,2,SEEK_CUR); // moves offset by another 2
        printf("%c",ch);
    }