fang_dejavu
fang_dejavu

Reputation: 626

Counting unknown numbers of chars from a file in C

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

Upvotes: 2

Views: 6696

Answers (5)

Chris Cooper
Chris Cooper

Reputation: 17564

EDIT: You probably want to read the answers below this.

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);
}

Upvotes: 2

sum1stolemyname
sum1stolemyname

Reputation: 4552

FILE *source = fopen("File.txt", "r");
fseek(source, 0, SEEK_END);
int byteCount = ftell(source);
fclose(source);

Upvotes: 5

Potatoswatter
Potatoswatter

Reputation: 137770

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.

Upvotes: 8

mouviciel
mouviciel

Reputation: 67831

/* 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);

Upvotes: 2

Tom
Tom

Reputation: 45104

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.

Upvotes: 1

Related Questions