Sunday, October 30, 2022

[FIXED] How to read until end of file C, fscanf

Issue

What i read from a file: a P1/ s/ e/ t etc. / for different line. After specific letters(like 'a') come some data i have to collect so i don't want to use fgets. It doesn't end running. Could you help me, please?

char com[21];
fscanf(src,"%s",com);
while(com!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    fscanf(src,"%s",com);
}

Solution

Simple way is to test if fscanf() succeeded as the loop condition and you don't need a fscanf() before the loop:

char com[21];

while(fscanf(src,"%20s",com) == 1)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
}

fscanf() returns the number of items successfully scanned. So, you don't need to check if it' returned EOF.

Note that I changed the format string to avoid buffer overflow. I suggest you use fgets() instead of fscanf() (and remember to take care of newline chars if it matters).



Answered By - P.P
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.