tags:

views:

121

answers:

5

I'm looking for a easy way to count the unknown number of characters in a file using C language. thanks for your help

+4  A: 

The POSIX way (probably what you want):

off_t get_file_length( FILE *file ) {
    fpos_t position; // fpos_t may be a struct and store multibyte info
    off_t length; // off_t is integral type, perhaps long long

    fgetpos( file, &position ); // save previous position in file

    fseeko( file, 0, SEEK_END ); // seek to end
    length = ftello( file ); // determine offset of end

    fsetpos( file, &position ); // restore position

    return length;
}

The standard C way (to be pedantic):

long get_file_length( FILE *file ) {
    fpos_t position; // fpos_t may be a struct and store multibyte info
    long length; // break support for large files on 32-bit systems

    fgetpos( file, &position ); // save previous position in file

    if ( fseek( file, 0, SEEK_END ) // seek to end
        || ( length = ftell( file ) ) == -1 ) { // determine offset of end
        perror( "Finding file length" ); // handle overflow
    }

    fsetpos( file, &position ); // restore position

    return length;
}

If you want to know the number of multibyte characters, you need to read the entire file with eg fgetwc.

Potatoswatter
A: 

This should get you started if you need to count only some characters (for example, only printable characters)

while (fgetc(file_handler)!=EOF)
{
 //test condition here if neccesary.
  count++;
}

If you are looking for the size of the file, the fseek / ftell solution seems less syscall expensive.

Tom
Quite time-consuming
klez
Yes, quite. :( :(
Tom
+3  A: 
FILE *source = fopen("File.txt", "r");
fseek(source, 0, SEEK_END);
int byteCount = ftell(source);
fclose(source);
sum1stolemyname
+2  A: 
/* wc is used to store the result */
long wc;

/* Open your file */
FILE * fd = fopen("myfile", "r");

/* Jump to its end */
fseek(fd, 0, SEEK_END);

/* Retrieve current position in the file, expressed in bytes from the start */
wc = ftell(fd);

/* close your file */
fclose(fd);
mouviciel
`fd` is a good name for a file descriptor, which would be an `int`.
Potatoswatter
+1  A: 

You can keep reading characters until the end of a file by checking the result of a reading operation against EOF (end of file). Doing them one at a time also lets you gather other statistics about them.

char nextChar = getc(yourFilePointer);
int numCharacters = 0;

while (nextChar != EOF) {
    //Do something else, like collect statistics
    numCharacters++;
    nextChar = getc(yourFilePointer);
}
Chris Cooper
that helped a lot, thanks!
fang_dejavu