本文部分参考《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; }