使用c打印文件的最后n行

时间:2016-10-20 17:45:35

标签: c

下面是我的功能,用fp显示文件指针,num是要打印的行数。现在,它再次显示完整的文件,而不是必需的行,这是我不想要的。

void dispfile(FILE *fp, int num)
{

    long int pos;char s[100];
    int count;
    fseek(fp, 0, SEEK_END);
    pos=ftell(fp);

    while(pos)
    {
        fseek(fp, --pos, SEEK_SET);
        if(fgetc(fp)=='\n')
        {   
            if(count++ == num) 
            break;
        }
    }

    while(fgets(s, sizeof(s), fp))
    {
        printf("%s",s);
        //fputs(s, stdout);
    }

}

2 个答案:

答案 0 :(得分:2)

count未初始化。它包含相当不可预测的垃圾,条件count++ == num在不可预测的时刻得到满足(严格来说,你有UB)。

答案 1 :(得分:1)

你可以通过两次读取文件,第一次计算其行,第二次跳过一些行,然后打印到num行来完成。如果文件没有num行,则全部打印。假设s[]将保留文件中最长的一行。

void dispfile(FILE *fp, int num)
{
    int lines = 0;
    char s[100];

    rewind(fp);
    while(fgets(s, sizeof s, fp) != NULL) {
        lines++;                                // count the lines
    }

    rewind(fp);
    lines -= num;                               // lines to skip
    while(lines-- > 0) {
        if(fgets(s, sizeof s, fp) == NULL) {
            return;                             // unexpected EOF
        }
    }

    while(fgets(s, sizeof s, fp) != NULL) {     // print the rest
        printf("%s", s);                        // newline is already included
    }
}
相关问题