reading lines using fscanf

2019-01-18 01:05发布

问题:

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?

回答1:

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.



回答2:

Use fgets to get the line, and then do one sscanf to check for 9 elements, and if that fails then use sscanf again to check for the 8 element line.

If the format of the line is equal except one extra item, then remember that the scanf family of functions return the number of successfully scanned items. So it might be enough to just call sscanf once, and check if it returns 8 or 9.



回答3:

You have to use the fgets() function because your swag value in your array is currently set to null.



回答4:

and don't use & with string type (char arrays) data types with scanf

scanf("%s",name); //use it without "&" sign

reason:

A "string" in C is the address of a character buffer. You want scanf to fill the memory in the buffer, which is pointed to by the variable.

In contrast, an int is a block of memory, not an address. In order for scanf to fill that memory, you need to pass its address.



标签: c std scanf