C++获取文本文件字节数的一个小方法
1 调用ifstream打开一个文件
2 调用seekg将get pointer置为文件末尾,seekg(0, ios_base::end)
3 调用tellg获取总字节数,实际上获取的是get pointer相对于文件头的偏移字节数
4 重置get pointer,使其指向文件头,以便执行其他操作
以下代码摘自www.cplusplus.com
[cpp] view plaincopy
- #include <iostream>
- #include <fstream>
- using namespace std;
- int main () {
- int length;
- char * buffer;
- ifstream is;
- is.open ("test.txt", ios::binary );
- // get length of file:
- is.seekg (0, ios::end);
- length = is.tellg();
- is.seekg (0, ios::beg);
- // allocate memory:
- buffer = new char [length];
- // read data as a block:
- is.read (buffer,length);
- is.close();
- cout.write (buffer,length);
- return 0;
- }
对于ifstream对象的每一次read过后,可以调用ifstream::gcount获取读取的字节数,
gcount的返回值为streamsize,而streamsize是个整型,signed int或signed long
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: MFC怎样实现按回车键相当于点击指定按钮
- 下一篇: jni中如何传递字符串或者数组