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

来源:互联网 发布:精易编程助手怎么用 编辑:程序博客网 时间:2024/05/17 07:45

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

	
				
		
原创粉丝点击