Q:

C Program to Find the Number of Lines in a Text File

belongs to collection: C programs - File Handling

0

This C Program asks user to open a file and then displays the number of lines in that file.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C Program to Find the Number of Lines in a Text File - Source code

int main()
{
    FILE *fileptr;
    int count_lines = 0;
    char filechar[40], chr;
  
    printf("Enter file name: ");
    scanf("%s", filechar);
    fileptr = fopen(filechar, "r");
   //extract character from file and store in chr
    chr = getc(fileptr);
    while (chr != EOF)
    {
        //Count whenever new line is encountered
        if (chr == 'n')
        {
            count_lines = count_lines + 1;
        }
        //take next character from file.
        chr = getc(fileptr);
    }
    fclose(fileptr); //close file.
    printf("There are %d lines in %s  in a file\n", count_lines, filechar);
    return 0;
}

Program Output

Enter file name: reverse.c
There are 27 lines in reverse.c  in a file

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< C program to illustrate reading of data from a Fil...