如何查找文件中的字符数量而不遍历内容 [英] How to find number of characters in a file without traversing the contents

查看:146
本文介绍了如何查找文件中的字符数量而不遍历内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个项目中,我必须读取一个文件,而且我必须处理一个文件中的字符数量,并且有一个方法来获取字符数量,而不是逐个字符地读取它(否则我将不得不阅读文件两次,一次只是为了找到其中的字符数)。

甚至有可能吗?


  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆