Reputation: 155
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);
}
Upvotes: 2
Views: 30038
Reputation: 24905
Please note that fscanf
returns an integer
which can indicate EOF
when the End of File is reached. Please refer to the man pages for more detail.
Your code will have to modified like below:
char com[21];
int ret;
ret = fscanf(src,"%s",com);
while(ret!=EOF)
{
if(com[0]=='a')
fprintf(dest,"%s 1",com);
if(com[0]=='s')
fprintf(dest,"%s 2",com);
ret = fscanf(src,"%s",com);
}
Upvotes: 2
Reputation: 121427
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).
Upvotes: 4