Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding line size of each row in a text file

Tags:

c

How can you count the number of characters or numbers in each line? Is there something like a EOF thats more like a End of Line?

like image 358
MRP Avatar asked Jan 26 '10 02:01

MRP


People also ask

How to check length of a line in C?

Use the strlen() function provided by the C standard library string. h header file. char name[7] = "Flavio"; strlen(name); This function will return the length of a string as an integer value.

How do I determine the length of a text file?

One way is to use the LEN function. This function will return the number of characters in a cell. So, if you have a cell that contains the text "Hello", the LEN function will return 5. Another way to determine the length of a text file is to use the FIND function.

How do you get the size of a string in a file in C?

String Length in C Programming User can get the length of the string using strlen() function declared under the header file string. h . Size of the string will be counted with white spaces. this function counts and returns the number of characters in a string.


1 Answers

You can iterate through each character in the line and keep incrementing a counter until the end-of-line ('\n') is encountered. Make sure to open the file in text mode ("r") and not binary mode ("rb"). Otherwise the stream won't automatically convert different platforms' line ending sequences into '\n' characters.

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's 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;
}
like image 188
Sam Avatar answered Sep 22 '22 02:09

Sam