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

来源:互联网 发布:ubuntu 离线安装jre 编辑:程序博客网 时间:2024/05/18 03:31

1 调用ifstream打开一个文件

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

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

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

 

以下代码摘自www.cplusplus.com

[cpp] view plaincopy
  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 0
原创粉丝点击