Printing the first 10 line of a file in C

Viewed 1664

I'm new to programming in C. And I'm trying to print the first 10 lines of a text file. When I run my program with a text file containing 11 lines of text, only the first line is displayed. I'm not sure why it does that, but I suspect there is something wrong in my while loop. Can someone please help me?

#include <stdio.h>

int main(int argc, char *argv[]){
    FILE *myfile;
    char content;
    int max = 0;

    // Open file
    myfile = fopen(argv[1], "r");
    if (myfile  == NULL){
        printf("Cannot open file \n");
        exit(0);
}
    // Read the first 10 lines from file
    content  = fgetc(myfile);
    while (content != EOF){
        max++;
        if (max > 10)
            break;
        printf ("%c", content);
        content = fgetc(myfile);
    }
 
    fclose(myfile);
    return 0;
}
3 Answers

You have been already advised to use fgets. However, if your file has lines of unknown length, you may still want to use fgetc. Just make sure you count only newlines, not all characters:

int max = 0;
int content;
while ((content = fgetc(myfile)) != EOF && max < 10){
    if (content == '\n') max++;
    putchar(content);
}

fgetc() returns the next character in the file, not the next line. You probably want to use fgets() instead, which reads up to the next newline character into a buffer. Your code should probably end up with something like:

// allocate 1K for a buffer to read
char *buff = malloc(1024);
// iterate through file until we are out of data or we read 10 lines
while(fgets(buff, 1024, myfile) != NULL && max++ < 10) {
    printf("%s\n", buff);
}
free(buff);
// close your file, finish up...

Read more about fgets() here: https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

fgetc function reads the next character not the next ine. for reading the number of lines you should use fgets function. this function reads the full string till the end of the one line and stores it in a string. your code Shuld be as:-

#include <stdio.h>

int main(int argc, char *argv[])
{
    FILE *myfile;
    char content[200];
    int max = 0;

    // Open file
    myfile = fopen(argv[1], "r");
    if (myfile == NULL)
    {
        printf("Cannot open file \n");
        exit(0);
    }
    // Read the first 10 lines from file
    fgets(content, 200, myfile);
    while (content != EOF)
    {
        max++;
        if (max > 10)
            break;
        printf("%s", content);
        fgets(content, 200, myfile);
    }

    fclose(myfile);
    return 0;
}
Related