c++文件偏移

 1 #include <iostream>
 2 #include <fstream>
 3 #include <cassert>
 4 
 5 using namespace std;
 6 int main()
 7 {
 8     ifstream in("test_data.txt");
 9     assert(in.is_open());
10 
11     //基地址为文件结束处,偏移地址为0,于是指针定位在文件结束处
12     in.seekg(0, ios::end);
13     //sp为定位指针,因为它在文件结束处,所以也就是文件的大小
14     streampos sp = in.tellg();    
15     cout<<"file size:"<<sp<<endl;
16 
17     //基地址为文件末,偏移地址为负,于是向前移动sp/3个字节
18     in.seekg(-sp/3, ios::end);   
19     streampos sp2 = in.tellg();
20     cout<<"from file to point:"<<sp2<<endl;
21 
22     //基地址为文件头,偏移量为0,于是定位在文件头; 从头读出文件内容
23     in.seekg(0, ios::beg);
24     cout<<in.rdbuf()<<endl;//由于偏移从头开始,所有输出文件的所有内容    
25 
26     //从sp2开始读出文件内容,即sp2后面的所有内容
27     in.seekg(sp2);
28     cout<<in.rdbuf()<<endl; 
29 
30     in.close();
31 
32     return 0;
33 }
原文地址:https://www.cnblogs.com/yyxayz/p/4078802.html