Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why should i put SEEK_SET twice

I want to modify some vowels of a file by "5". The following code works. However i do not understand why should I put fseek twice.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void print_file_contents(const char *filename) 
{
    FILE *fp;
    char letter;

    if((fp=fopen(filename,"r+"))==NULL)
    {
        printf("error\n");
        exit(1);
    }

    fseek(fp,0,SEEK_END);
    int size=ftell(fp);
    rewind(fp);

    for(int i=0;i<size;i++)
    {
        fseek(fp,i,SEEK_SET);
        letter=fgetc(fp);
    
        if((letter=='a') || (letter=='e') || (letter=='i'))
        {
            fseek(fp,i,SEEK_SET); // WHY THIS FSEEK ?
            fwrite("5",1,sizeof(char),fp);
        }

    }

    fclose(fp);
}

int main(int argc, char *argv[])
{
    print_file_contents("myfile");
    return 0;
}

In my opinion, the first fseek(fp, i, SEEK_SET) is used to set the file position indicator to the current character being processed, so that the character can be read using fgetc. Hence, the cursor is updated everytime so there is no need to add an other fseek(fp,i,SEEK_SET);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The fgetc advanced the file position; if you want to replace the character you just read, you need to rewind back to the same position you were in when you read the character to replace.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading