【发布时间】:2010-04-15 13:23:41
【问题描述】:
我正在寻找一种使用 C 语言计算文件中未知字符数的简单方法。感谢您的帮助
【问题讨论】:
-
你的意思是你想知道文件的大小吗?或者您不想知道文件中有多少不同的字符?
-
未知?你的意思是编译时未知?
我正在寻找一种使用 C 语言计算文件中未知字符数的简单方法。感谢您的帮助
【问题讨论】:
POSIX 方式(可能是你想要的):
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;
}
标准的C方式(有点迂腐):
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;
}
如果你想知道多字节字符的数量,你需要读取整个文件,例如fgetwc。
【讨论】:
fsetpos() 不是使用rewind() 更友好一些
FILE *source = fopen("File.txt", "r");
fseek(source, 0, SEEK_END);
int byteCount = ftell(source);
fclose(source);
【讨论】:
编辑:您可能想阅读下面的答案。
通过对照EOF(文件结束)检查读取操作的结果,您可以一直读取字符直到文件结束。一次做一个还可以让您收集有关它们的其他统计信息。
char nextChar = getc(yourFilePointer);
int numCharacters = 0;
while (nextChar != EOF) {
//Do something else, like collect statistics
numCharacters++;
nextChar = getc(yourFilePointer);
}
【讨论】:
/* 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);
【讨论】:
fd 是一个文件描述符的好名字,应该是 int。
如果您只需要计算某些字符(例如,仅可打印的字符),这应该可以帮助您开始
while (fgetc(file_handler)!=EOF)
{
//test condition here if neccesary.
count++;
}
如果您正在寻找文件的大小,fseek / ftell 解决方案似乎不太昂贵。
【讨论】: