简体   繁体   English

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

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

Im trying to figure out how to read specific lines from file, ie I have file with 40 lines and I want to print only the lines 3,4,17,24 out from the file, by the line number. 我试图弄清楚如何从文件中读取特定的行,即我有40行的文件,我只想按行号从文件中打印第3、4、17、24行。 What I know right know is just how to print the whole file line by line with a condition of != EOF. 我所知道的只是如何在!= EOF条件下逐行打印整个文件。 What I'm trying to get at the end is a program that can read file's decided lines and print them out. 我最后想要得到的是一个程序,该程序可以读取文件的已决定行并将其打印出来。 Thanks a lot. 非常感谢。

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

edit: the next step after that is getting specific colums from the decided lines, What I mean by cloumns is that every line has ',' between colums, my idea was to try with strtok(), but if you got any better idea i'd thank you. 编辑:下一步是从确定的行中获取特定的列,我所说的cloumns是列之间的每一行都有',',我的想法是尝试使用strtok(),但是如果您有更好的主意,会谢谢你的。

Keep a count of lines read. 保持读取行数。

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

I also fixed your bug; 我还修复了您的错误; fgets() returns NULL not EOF on end of file. fgets()在文件末尾返回NULL而不是EOF

A bit off-topic answer: It is a nice exercise to do this in C directly, but it is actually error prone. 有点离题的答案:直接在C中执行此操作是一个不错的练习,但实际上容易出错。 There are much better tools to filter lines from a file. 有更好的工具来过滤文件中的行。

ed and sed would be my favorites here: edsed将是我的最爱:

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

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

or with a list of numbers (output in ed with line numbers) 或带有数字列表(以行号在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