Counting unknown character numbers from file in C

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

+2


a source to share


5 answers


EDIT: You probably want to read the answers below.

You can keep reading characters to the end of the file by checking the result of the read operation from EOF

(end of file). By doing them one at a time, you can also collect other statistics about them.



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

while (nextChar != EOF) {
    //Do something else, like collect statistics
    numCharacters++;
    nextChar = getc(yourFilePointer);
}

      

+2


a source


POSIX path (maybe 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;
}

      

Standard way C (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 whole file, for example fgetwc

.

+8


a source


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

      

+5


a source


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

      

+2


a source


This should start if you only need to count some characters (e.g. printable characters only)

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

      

If you're looking for file size, fseek / ftell's solution looks less economical.

+1


a source







All Articles