Finding the line size of each line in a text file

How can you count the number of characters or numbers in each line? Is there something like an EOF similar to the end of a line?

+5
source share
5 answers

You can iterate over each character in the string and continue to increment the counter until the end of the string ( '\n') is encountered . Be sure to open the file in text mode ( "r"), and not in binary mode ( "rb"). Otherwise, the stream will not automatically convert the line ending sequences of different platforms into characters '\n'.

Here is an example:

int charcount( FILE *const fin )
{
    int c, count;

    count = 0;
    for( ;; )
    {
        c = fgetc( fin );
        if( c == EOF || c == '\n' )
            break;
        ++count;
    }

    return count;
}

Here is an example program to test the above function:

#include <stdio.h>

int main( int argc, char **argv )
{
    FILE *fin;

    fin = fopen( "test.txt", "r" );
    if( fin == NULL )
        return 1;

    printf( "Character count: %d.\n", charcount( fin ) );

    fclose( fin );
    return 0;
}
+5
source

, fgets.

char *fgets(char *restrict s, int n, FILE *restrict stream);

fgets() , s, n-1 ,   s . .

, . , .

:

: \n - ( ).

, :

ASCII LF (Line feed, 0x0A, 10 ) CR ( , 0x0D, 13 ) CR, LF (CR + LF, 0x0D 0x0A); . CR + LF . : , , , .

* LF:    Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others
* CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS
* CR:    Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9

, , .

+2

\n - C. , #, - # Environment.EndLine .

, ( ), strlen(line), . 1, '\n'.

, , strlen() .

+1

, b fopen(), , '\n', . , '\n'. '\n', .

:

count := 0
c := next()
while c != EOF and c != '\n'"
    count := count + 1

. next() - , .

fgets() :

char buf[SIZE];
count = 0;
while (fgets(buf, sizeof buf, fp) != NULL) {
    /* see if the string represented by buf has a '\n' in it,
       if yes, add the index of that '\n' to count, and that's
       the number of characters on that line, which you can
       return to the caller.  If not, add sizeof buf - 1 to count */
}
/* If count is non-zero here, the last line ended without a newline */
+1

, " " ( ? ?), , . , ( ).

. fgets , (strtok, strtod ..) . , , .

, :

    max=0; i=0;
    do 
        if ((c=fgetc(f))!= EOF && c!='\n') i++; 
        else { 
            if (i>max) max=i;
            i=0;
            }
    while (c!=EOF);
    return max;

Note. In practice, it is enough to have an upper bound for maximum length. A dirty solution would be to use file size as the upper bound for the maximum line length.

0
source

All Articles