Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

c - reading lines using fscanf

hi i have a file which contains following lines:

wwa weweweof ewewe wdw:

      1    11 ms    <1 ms    <1 ms  174.78.134.1  
      2    11 ms    <1 ms    <1 ms  174.78.134.1 
      3     5 ms    <1 ms    <1 ms  x58trxd00.abcd.edu.com [143.71.290.42] 
      4    11 ms    <1 ms    <1 ms  174.78.134.1 

i am using

    if(linecount == 8)
    while( fscanf(fp, "%d %s %s %s %s  %s %s",&a1,&a2,&a3,&a4,&a5,&a6,&a7,&a8) != EOF ){  
          printf("%s",ch);
        } 

    else if (linecount == 9){
       while( fscanf(fp, "%d %s %s %s %s  %s %s %s",&a1,&a2,&a3,&a4,&a5,&a6,&a7,&a8,&a9) != EOF ){  
          printf("%s",ch);
       }
    }

how do i check if the line rows in the file contain 8 or 9 elements, so that i can run the above else-if statements accordingly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

reading lines using fscanf

No.

But I though it was a good idea because...

No.


Reading lines is done using the fgets() function (read the funny manual):

char buf[LINE_MAX];
while (fgets(buf, sizeof buf, file) != NULL) {
    // process line here
}

Then, you can parse it using sscanf() (not preferred) or sane functions like strchr() and strtok_r() (preferred). It is also worth not(h)ing that the return value of scanf() (docs) is not EOF, but the number of entities successfully read. So, a lazy approach for parsing the string may be:

if (sscanf(buf, "%s %s %s %s %s %s %s %s %s", s1, s2, ...) < 9) {
    // there weren't 9 items to convert, so try to read 8 of them only
}

Also note that you better use some length-limitation with the %s conversion specifier in order to avoid buffer overflow errors, like this:

char s1[100];
sscanf(buf, "%99s", s1);

Likewise, you should not use the & address-of operator when scanning (into) a string - the array of char already decays into char *, and that is exactly what the %s conversion specifier expects - the type of &s1 is char (*)[N] if s1 is an array of N chars - and a mismatching type makes scanf() invoke undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...