C++获取文本文件字节数的一个小方法

1 调用ifstream打开一个文件

2 调用seekg将get pointer置为文件末尾,seekg(0, ios_base::end)

3 调用tellg获取总字节数,实际上获取的是get pointer相对于文件头的偏移字节数

4 重置get pointer,使其指向文件头,以便执行其他操作

 

以下代码摘自www.cplusplus.com

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <fstream>  
  3. using namespace std;  
  4.   
  5. int main () {  
  6.   int length;  
  7.   char * buffer;  
  8.   
  9.   ifstream is;  
  10.   is.open ("test.txt", ios::binary );  
  11.   
  12.   // get length of file:  
  13.   is.seekg (0, ios::end);  
  14.   length = is.tellg();  
  15.   is.seekg (0, ios::beg);  
  16.   
  17.   // allocate memory:  
  18.   buffer = new char [length];  
  19.   
  20.   // read data as a block:  
  21.   is.read (buffer,length);  
  22.   
  23.   is.close();  
  24.   
  25.   cout.write (buffer,length);  
  26.   
  27.   return 0;  
  28. }  
  29.    

 

对于ifstream对象的每一次read过后,可以调用ifstream::gcount获取读取的字节数,

gcount的返回值为streamsize,而streamsize是个整型,signed int或signed long

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值