Welcome

首页 / 软件开发 / C++ / C++中 随机访问(random access) 流(stream) 详解

C++中 随机访问(random access) 流(stream) 详解2014-11-20随机访问流, 使用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 << "
";return 0;}

输出(文本):

CarolineWendySpikeWinny9 12 16 21
作者:csdn博客 Spike_King