繁体   English   中英

从C中的文件读取特定的行和列

[英]Reading specific lines and colums from file in C

我试图弄清楚如何从文件中读取特定的行,即我有40行的文件,我只想按行号从文件中打印第3、4、17、24行。 我所知道的只是如何在!= EOF条件下逐行打印整个文件。 我最后想要得到的是一个程序,该程序可以读取文件的已决定行并将其打印出来。 非常感谢。

void Analyzer(char* filename, int *rows, int *cols) {
    char s[99];
    FILE *fin = fopen(filename, "r");
    if (fin == NULL)
    {
        printf("Cannot open file.\n");
        return;
    }
    while (fgets(s, 99, fin) != EOF) {
        printf("%s", s);
    }
    fclose(fin);
}

编辑:下一步是从确定的行中获取特定的列,我所说的cloumns是列之间的每一行都有',',我的想法是尝试使用strtok(),但是如果您有更好的主意,会谢谢你的。

保持读取行数。

int linecounter = 0;
while (fgets(s, 99, fin) != NULL) {
    switch (++linecounter){
        case 3: case 4: case 17: case 24:
            printf("%s", s);
    }
}

我还修复了您的错误; fgets()在文件末尾返回NULL而不是EOF

有点离题的答案:直接在C中执行此操作是一个不错的练习,但实际上容易出错。 有更好的工具来过滤文件中的行。

edsed将是我的最爱:

printf %s\\n 3 4 17 24 q| ed txtfile

sed `printf \ \-e%s\  3p 4p 17p 24p d` < txtfile

或带有数字列表(以行号在ed中输出)

(cat lnums | while read l; do printf %sn\\n "$l"; done; printf %s\\n q)| ed txtfile

args=`sed -e 's/^[0-9]*$/-e &p/' -e '$a -e d' lnums | tr '\n' ' '`; sed $args txtfile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM