0

How do I read and print just n(10) lines in a file and not whole file.

#include<stdio.h>
#include<string.h>

int main()
{
        char line[50];
        FILE *datafile;
        datafile = fopen("/data3", "r");
        while(fgets(line,sizeof line,datafile)!=NULL)
        printf(" %s\n", line);
        fclose(datafile);
        return 0;
}
3
Contributors
7
Replies
10
Views
6 Years
Discussion Span
Last Post by Narue
0

something like this

#include<stdio.h>
#include<string.h>

int main()
{
        char line[50];
        FILE *datafile;
        datafile = fopen("/data3", "r");
        for(i=0; i<line; i++)
        printf(" %s\n", i);
        fclose(datafile);
        return 0;
}

Edited by mike_2000_17: Fixed formatting

0

Simples, for the loop that reads in the lines, have a variable that increments in each loop and causes the loop to break when it reaches 10.

0

No, not at all. Something like this:

FILE *datafile = fopen("/data3", "r");

if (datafile != NULL) {
    char line[50];
    int i;

    for (i = 0; i < 10 && fgets(line, sizeof line, datafile) != NULL; i++)
        fputs(line, stdout);

    fclose(datafile);
}
0

Now if I wanted to read from say line 20 to EOF. Just change the for loop

for (i = 20; i > 20 && fgets(line, sizeof line, datafile) != NULL; i++)
        fputs(line, stdout);
0

tried this for loop, to read from 16 lines to end of file but not getting any output.
how do i get it to display from line 16 to EOF

FILE *datafile = fopen("/data3", "r");
if (datafile != NULL)
{
    char line[53];
    int i;

    for (i = 16; i > 16 && fgets(line, sizeof line, datafile) != NULL; i++)
        fputs(line, stdout);

    fclose(datafile);
}
0

how do i get it to display from line 16 to EOF

Read 16 lines and throw them away, then start your printing loop.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.