gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:14:59 28 4
gpt4 key购买 nike

我正在寻找一种使用 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读取整个文件。

关于计算 C 文件中未知数量的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2645598/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com