首页 > 编程语言 > 详细

c++文件偏移

时间:2014-11-06 16:18:05      阅读:285      评论:0      收藏:0      [点我收藏+]
 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 }

 

c++文件偏移

原文:http://www.cnblogs.com/yyxayz/p/4078802.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!