如何查找文件中的字符数量而不遍历内容 [英] How to find number of characters in a file without traversing the contents
问题描述
甚至有可能吗?
FILE * fp = ... / *解决方案
照常开启* /;
fseek(fp,0L,SEEK_END);
size_t fileSize = ftell(fp);
然而,这会返回文件中的字节数,而不是字符的数量。这是不一样的,除非编码被认为是每个字符一个字节(例如ASCII)。
你需要倒带文件回到开始你知道这个尺寸后:
fseek(fp,0L,SEEK_SET);
In a project, I have to read a file, and i have to work with the number of characters in a file, and is there a way to get number of characters without reading it character by character (otherwise i will have to read the file twice, once just to find the number of characters in it).
Is it even possible?
You can try this:
FILE *fp = ... /*open as usual*/;
fseek(fp, 0L, SEEK_END);
size_t fileSize = ftell(fp);
However, this returns the number of bytes in the file, not the number of characters. It is not the same unless the encoding is known to be one byte per character (e.g. ASCII).
You'd need to "rewind" the file back to the beginning after you've learned the size:
fseek(fp, 0L, SEEK_SET);
这篇关于如何查找文件中的字符数量而不遍历内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!