从C中的文件计算未知数量的字符

时间:2010-04-15 13:23:41

标签: c file

我正在寻找一种使用C语言计算文件中未知字符数的简便方法。谢谢你的帮助

5 个答案:

答案 0 :(得分:8)

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读取整个文件。

答案 1 :(得分:5)

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

答案 2 :(得分:2)

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

答案 3 :(得分:2)

编辑:你可能想阅读下面的答案。

通过检查针对EOF(文件结尾)的读取操作的结果,您可以继续读取字符直到文件末尾。一次执行一个也可以收集有关它们的其他统计信息。

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

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

答案 4 :(得分:1)

如果您只需要计算某些字符(例如,只能打印字符)

,这应该可以帮助您入门
while (fgetc(file_handler)!=EOF)
{
 //test condition here if neccesary.
  count++;
}

如果您正在寻找文件的大小,那么fseek / ftell解决方案似乎不那么昂贵。