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
2010-04-15 13:28:18
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
2010-04-15 13:29:20
Quite time-consuming
klez
2010-04-15 13:30:21
Yes, quite. :( :(
Tom
2010-04-15 13:32:03
+3
A:
FILE *source = fopen("File.txt", "r");
fseek(source, 0, SEEK_END);
int byteCount = ftell(source);
fclose(source);
sum1stolemyname
2010-04-15 13:30:02
+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
2010-04-15 13:30:11
`fd` is a good name for a file descriptor, which would be an `int`.
Potatoswatter
2010-04-15 14:50:37
+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
2010-04-15 13:32:11