1

对于即将到来的 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功能将被跳过。

额外信息

一些评论让我回去仔细检查。

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

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

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

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

4

1 回答 1

2

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

这里有更正确的方法

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

    }
}
于 2011-09-09T02:24:55.350 回答