如何使用c代码查找文件的尾部

时间:2016-01-16 15:15:46

标签: c file

我编写代码来查找尾部,但是,它有一个例外,当我尝试将整行打印为尾部时,它不会打印起始字符。 例如如果我的文件有14行,并且我输入的#include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]) { FILE *in, *out; int count = 0,lines; long int pos; char s[100]; char ch,c; if(argc<2) { printf("Arguments which is to be passed should be 2"); } else if(argc>2) { printf("too many argumnets are passed"); } in = fopen("anj.txt", "r"); out = fopen("output.txt", "w"); if(in==NULL || out==NULL) { printf("unable to open"); exit(0); } else { int n=atoi(argv[1]); if(n>=1) { fseek(in, 0, SEEK_END); pos = ftell(in); while (pos) { fseek(in, --pos, SEEK_SET); if (fgetc(in) == '\n') { //count=count+1; if (count++==n) break; } } if(count<n) { printf("no. of lines in file %d is less than enterd",count); } c = fgetc(in); while (c != EOF) { fputc(c, out); c = fgetc(in); } } else printf("renter the value of n"); } fclose(in); fclose(out); return 0; } 的值也是14,那么它将不会打印起始字符。

请帮助修改我的代码:

{{1}}

2 个答案:

答案 0 :(得分:1)

如果行数与输入的值相同,则代码将读取文件中的第一个字符,由fgetc使用,并因pos == 0而结束循环!

在这个角落情况的while循环之后添加此检查:

if (pos == 0)
{
    fseek(in, 0, SEEK_SET);
}

答案 1 :(得分:0)

如果通过 tail 表示文件的最后一行,则可以更轻松地获取文件的最后一行,并将其写入输出文件使用fgets()`:

int CountLines(FILE *fp);

int main(void)
{
    FILE *in, *out;
    char string[509];
    char input[80];
    char *dummy;
    char *fmt = "%[^\n]%*c";
    int count=0;
    int index = 0;
    int tailCnt=0;

    in = fopen("anj.txt", "r");
    out = fopen("output.txt", "w");
    if(in==NULL || out==NULL)
    {
        printf("unable to open");
        exit(0);
    }
    else
    {
        //get count of lines
        tailCnt = -1;
        count = CountLines(in);
        rewind (in);
        while((tailCnt<=0) || (tailCnt > count))
        {
            printf("File has %d lines.\nEnter lines from bottom of file to output (1 to %d).\n", count, count);

            scanf(fmt, input);
            tailCnt = strtol(input, &dummy, 10);
        }
        while(fgets(string, 100, in)) 
        {
            if(index >= (count-tailCnt))
            {
                fputs(string, out);
            }
            index++;

        }
        //check for fgets() error
        if(errno != 0)
        {
             printf("Error returned from fgets().  Exiting\n");
             return 0;
        }
    }
    fclose(in);
    fclose(out);
    return 0;
}

int CountLines(FILE *fp)//simple example line count, 
{                       //no error checking...
    int count=0;
    char line[509] = {0};//ANSI compatibility requires a compiler to accept minimum of 509 characters

    while(fgets(line, 509, fp)) count++;

    return count;

}

针对 anj.txt 的角落情况0,1和17进行了测试:

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11
This is line 12
This is line 13
This is line 14
This is line 15
This is line 16
This is line 17