What is the easiest way to count the newlines in an ASCII file?

前端 未结 5 948
一生所求
一生所求 2020-11-30 10:01

Which is the fastest way to get the lines of an ASCII file?

5条回答
  •  执念已碎
    2020-11-30 10:48

    Here's a solution based on fgetc() which will work for lines of any length and doesn't require you to allocate a buffer.

    #include 
    
    int main()
    {
        FILE                *fp = stdin;    /* or use fopen to open a file */
        int                 c;              /* Nb. int (not char) for the EOF */
        unsigned long       newline_count = 0;
    
            /* count the newline characters */
        while ( (c=fgetc(fp)) != EOF ) {
            if ( c == '\n' )
                newline_count++;
        }
    
        printf("%lu newline characters\n", newline_count);
        return 0;
    }
    

提交回复
热议问题