首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >c++ fstream流seekg()重定位问题

c++ fstream流seekg()重定位问题

作者头像
全栈程序员站长
发布2022-06-28 14:35:40
发布2022-06-28 14:35:40
1K0
举报

大家好,又见面了,我是你们的朋友全栈君。

在看c++中fstream时,突然想到一个问题。当读取完整个文件之后如果再想读取一遍该如何去写?首先想到seekg()函数把读指针重定位到文件开头。但是我试了一下发现指针并没有移动,后来才搞清楚原来是当读指针指到EOF后就没办法再进行指针的控制了。

代码语言:javascript
复制
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
	fstream outFile("test.txt");
	if(!outFile.is_open())
	{
		exit(EXIT_FAILURE);
	}

	string str;
	int x = 3;
	while (x--)
	{
		cin >> str;
		str += "\r\n";
		outFile.write(str.c_str(), str.length());
	}
	outFile.close();

	fstream inFile;
	inFile.open("test.txt");
	if (!inFile.is_open())
	{
		cout << "open infile error" << endl;
	}
	
	char buffer[32];
	int size = sizeof(buffer);
	while (inFile.getline(buffer, size))
	{
		cout << buffer << endl;
	}

	cout << "second" << endl;
	inFile.clear();
	inFile.seekg(0, ios::beg);
	string read_line;
	while (getline(inFile, str))
	{
		cout << str << endl;
	}

	inFile.close();

	system("pause");
	return 0;
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/132945.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年6月1,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档