Barara Barara - 1 month ago 11
C Question

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 number of lines to print. Right now, it again displays the complete file, not required 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

The count is not initialized. It contains rather unpredictable garbage, and the condition count++ == num is satisfied in an unpredictable moment (strictly speaking, you have the UB).