使用 fscanf 读取行 [英] reading lines using fscanf

查看:61
本文介绍了使用 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 

我正在使用

    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);
       }
    }

如何检查文件中的行行是否包含 8 或 9 个元素,以便我可以相应地运行上述 else-if 语句?

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?

推荐答案

使用 fscanf 读取行

reading lines using fscanf

没有

但我认为这是个好主意,因为...

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

没有

阅读行是使用 fgets() 函数完成的(阅读有趣的手册):

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
}

然后,您可以使用 sscanf()(不是首选)或像 strchr()strtok_r() 这样的理智函数来解析它(首选).同样值得一提的是 scanf() 的返回值(docs) 是不是 EOF,而是成功读取的实体数量.因此,解析字符串的懒惰方法可能是:

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
}

另请注意,您最好在 %s 转换说明符中使用一些长度限制,以避免缓冲区溢出错误,如下所示:

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);

同样,在扫描(进入)字符串时,您不应使用 & address-of 运算符 - char 数组已经衰减为 char *,并且正是 %s 转换说明符所期望的 - &s1 的类型是 char (*)[N] 如果 s1 是 N 个 char 的数组 - 不匹配的类型使 scanf() 调用未定义的行为.

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.

这篇关于使用 fscanf 读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆