大家好,又见面了,我是你们的朋友全栈君。
在看c++中fstream时,突然想到一个问题。当读取完整个文件之后如果再想读取一遍该如何去写?首先想到seekg()函数把读指针重定位到文件开头。但是我试了一下发现指针并没有移动,后来才搞清楚原来是当读指针指到EOF后就没办法再进行指针的控制了。
#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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有