C++获取文件大小

 1 #include <iostream>

 2 #include <string>

 3 #include <vector>

 4 #include <fstream>

 5 

 6 using namespace std;

 7 

 8 int main(int argc, char *argv[])

 9 {

10     ifstream ifs("test.txt");

11     

12     ifs.seekg(0, ios::end);   //设置文件指针到文件流的尾部

13     streampos pos = ifs.tellg();  //读取文件指针的位置

14 

15     cout << "The file size: " << pos << " byte" << endl;

16     ifs.close();  // 关闭文件流

17 

18     return 0;

19 }

/*
总结:

注意:
1、读取的时候是以byte为单位进行的。
2、basic_istream<Elem, Tr>& seekg(off_type _Off, ios_base::seekdir _Way);
可以看到第一个参数为偏移量,它是相对于第二个参数的偏移量。

遵循x坐标的原理,即把第二个参数当做原点。
若偏移量为负,则在第二个参数的左边;若偏移量为正,则在第二个参数的右边。
*/

根据上述可以写成:

ifs.seekg(-1, ios::end);   // 此时文件指针指向末尾的前一字节

你可能感兴趣的:(文件大小)