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

来源:互联网 发布:javbus2域名发布地址 编辑:程序博客网 时间:2024/05/21 07:48

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

1 调用ifstream打开一个文件

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

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

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

#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; }  


原创粉丝点击