reading lines using fscanf

后端 未结 4 1090
有刺的猬
有刺的猬 2020-12-09 13:51

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          


        
相关标签:
4条回答
  • 2020-12-09 14:35

    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.

    0 讨论(0)
  • 2020-12-09 14:43

    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.

    0 讨论(0)
  • 2020-12-09 14:45

    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.

    0 讨论(0)
  • 2020-12-09 14:45

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

    0 讨论(0)
提交回复
热议问题