tariq tariq - 3 months ago 25
C Question

Count number of line using C

Is there a way to count the number of lines in my file using C?

Answer

If you want to perform this programmatically, open the file in text mode and perform fgetc() operation until you reach end of file. Keep a count of number of times fgetc was called.

    FILE *fp = fopen("myfile.txt");
    int ch;
    int count=0;
    do
    {
        ch = fgetc(fp);
        if(ch == '\n') count++;   
    } while( ch != EOF );    

    printf("Total number of lines %d\n",count);