Counting unknown character numbers from file in C
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 to share
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 to share