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

Recommended Answers

All 7 Replies

Use a for loop instead of a while loop, perhaps?

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

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.

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

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

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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.