tariq tariq - 2 months ago 7x
C Question

Count number of line using C

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


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;
        ch = fgetc(fp);
        if(ch == '\n') count++;   
    } while( ch != EOF );    

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