Barara Barara - 1 month ago 19
C Question

i want to print last n number of lines of a file using c

below is my function to display with fp the file pointer and num be the nmber of lines to print ... Right now it again displays the cmplt file not reqired lines which i do not want.

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

}

Answer

You can do it by reading the file twice, the first time to count its lines, the second to skip some lines and then print up to num lines. If the file does not have num lines, all are printed. Assuming s[] will hold the longest line in the file.

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