【问题标题】:strstr C function is functioning abnormallystrstr C 函数运行异常
【发布时间】:2011-11-13 10:50:51
【问题描述】:

对于即将到来的 C 项目,目标是读取 CSV 文件,其中前两行列出行和列的长度,如

attributes: 23
lines: 1000
e,x,y,n,t,l,f,c,b,p,e,r,s,y,w,w,p,w,o,p,n,y,p
e,b,y,y,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,s,m
e,x,f,y,t,l,f,w,n,w,t,b,s,s,w,w,p,w,o,p,n,v,d
e,s,f,g,f,n,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,v,u

问题是,我不知道未来的文件输入是否具有相同的行/列长度,所以我正在实现一个 determineFormat 函数来读取前两行,这将用于构建数据结构。

为了做到这一点,我需要将一个子字符串匹配到当前行。如果匹配,则使用fscanf 读取该行并提取长度整数。但是,此代码不起作用,因为整个 strstr 函数在 ddd 中被跳过。

int lineCount, attrCount; //global variables

void determineFormats(FILE *incoming){

    char *curLine= emalloc(CLINPUT);
    int i;
    char *ptr=NULL;

    for (i=0; i<2; i++){
        if (fgets(curLine, CLINPUT, incoming) != NULL){
            ptr= strstr(curLine, "attrib");  //this line is skipped over

            if (ptr!= NULL)
                fscanf(incoming, "attributes: %d", &attrCount);

            else 
                fscanf(incoming, "lines: %d", &lineCount);  

        }
    }

    printf("Attribute Count for the input file is: %d\n", attrCount);
    printf("Line count is: %d\n", lineCount);

}

我对 if/else 块的想法是因为这个函数只有两行感兴趣,而且它们都在文件的开头,只需扫描每一行并测试字符串是否匹配。如果是,则运行非空条件,否则执行另一个条件。但是,在这种情况下,strstr 函数将被跳过。

额外信息

一些cmets让我回去仔细检查。

CLINPUT 定义为 100,或者大约是要从每行读取的字符数的 40%。

这是调用 ptr= strstr(curLine, "attrib"); 时 ddd 的输出:

0xb7eeaff0 in strstr () from /lib/libc.so.6
Single stepping until exit from function strstr,
which has no line number information.

一旦发生这种情况,行指示器就会消失,并且从该点单步执行 (F5) 返回到调用函数。

【问题讨论】:

  • 呃,这不是 CSV 文件。 Comma S分隔的Values
  • stackoverflow 的粗体迷你标记中的错误 =) 应该使用非贪婪的正则表达式
  • 是的......我认为这仍然是重点:)
  • 是的。您的定义是 100% 正确的。很高兴看到网站中的错误。
  • 你忘了释放内存...

标签: c text-parsing strstr


【解决方案1】:

strstr 运行良好。问题是 fscanf 将读取 next 行,因为当前已经读取。

这里有更正确的方法

for (i=0; i<2; i++){
    if (fgets(curLine, CLINPUT, incoming) != NULL){
        if (strstr(curLine, "attributes:")) {
            sscanf(curLine, "attributes: %d", &attrCount);
        } else if (strstr(curLine, "lines:")) {
            sscanf(curLine, "lines: %d", &lineCount);  
        }

    }
}

【讨论】:

  • 这是从 fscanf 到 sscanf 的改变才成功的!谢谢!
猜你喜欢
  • 2013-05-30
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2020-06-27
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多