-1

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

}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Barara
  • 1
  • 3

2 Answers2

2

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).

user58697
  • 7,808
  • 1
  • 14
  • 28
1

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
    }
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56