您的位置:首页 > 编程语言 > C语言/C++

C++ 标准IO库 - 文件流操作【ifstream ofstream fstream】

2013-05-31 17:17 113 查看
本文部分参考《C++ Primer》

作者考虑不周之处,欢迎批评指正!O(∩_∩)O谢谢~

Louis.Wang

2013.5.31

*****************************************************

首先,fstream头文件定义了三种支持文件IO的类型:

(1)ifstream : 由istream派生而来,提供文件的读操作;

(2)ofstream :由ostream派生而来,提供文件的写操作;

(3)fstream : 由iostream派生而来,提供文件的读、写操作。

给定一个文件来读,在文件的末尾写一个新行,该行包括每一行的开头相对文件头的偏移量(不必写第一行的偏移量)。
#include "stdafx.h"
#include <iostream>
//#include "class.h"
#include <fstream>
#include <string> //getline包含在string头文件里

int _tmain(int argc, _TCHAR* argv[])
{
//A a;
//B b;
//a.print();
//b.print();
fstream inOut("F:\\C++Excise\\C++Excise\\class\\Debug\\copyOut.txt",
fstream::ate | fstream::in | fstream::out );

if (!inOut)
{
cerr << "Unable to open file! "<<endl;
return EXIT_FAILURE;
}

fstream::pos_type endmark = inOut.tellg();  //输入流中当前位置
inOut.seekg(0,inOut.beg);  //重新定位到文件头

int cnt = 0;
string line;
while ( inOut && inOut.tellg() != endmark
&&  getline(inOut,line) // 取出第一行
)
{
cnt += line.size() +1 ;

ifstream::pos_type mark = inOut.tellg(); //get输入流 当前位置
inOut.seekp(0,inOut.end);   //定位到文件末尾,向inOut 里面输入 每行开头的相对位置
inOut << cnt;

if(mark != endmark)
inOut << " ";
inOut.seekg(mark);
}
inOut.clear();
inOut.seekp(0,inOut.end);
inOut << "\n";
return 0;
}










                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐