PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

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

 October 30, 2022     c, eof, file     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing