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

C++ - 随机访问(random access) 流(stream) 的 详解 及 代码

2013-12-17 15:58 711 查看

随机访问(random access) 流(stream) 的 详解 及 代码

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17378303
随机访问流, 使用mark(标记)标注流的位置, 包含两种方法tell和seek;
tell, 是返回流mark的位置, 包含g和p两种版本.g表示get, 指输入流; p表示put, 指输出流;
seek, 是跳至流mark所指的位置, 也包含g和p两种版本;seek可以指定位置, 也可以指定偏移(offset);

代码如下:

/*  * cppprimer.cpp  *  *  Created on: 2013.11.28  *      Author: Caroline  */  /*eclipse cdt, gcc 4.8.1*/  #include <iostream> #include <fstream> #include <cstdlib>  using namespace std;  int main() { 	std::fstream inOut("copyOut", std::fstream::ate/*末尾*/ | std::fstream::in | std::fstream::out); 	if(!inOut) { 		std::cerr << "Unable to open file! " << std::endl; 		return EXIT_FAILURE; 	} 	std::fstream::pos_type end_mark = inOut.tellg(); 	inOut.seekg(0, std::fstream::beg); //重定位在起点 	std::size_t cnt(0); 	std::string line; 	while (inOut && inOut.tellg() != end_mark && 			getline(inOut, line)) 	{ 		cnt += line.size() + 1; 		std::fstream::pos_type mark = inOut.tellg(); //记住当前位置 		inOut.seekp(0, std::fstream::end); //跳至末尾 		inOut << cnt; 		if (mark != end_mark) inOut << " "; //除了最后一行, 均写入空格 		inOut.seekg(mark); //回到记录的地点 	} 	inOut.seekp(0, std::fstream::end); 	inOut << "\n"; 	return 0; }

输出(文本):

Caroline Wendy Spike Winny 9 12 16 21




本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387948
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: