使用Fstream同时读写
我正在学习如何从文件中读写。有一个问题,当我尝试写(例如,文件字母中 - )阅读或在文件中写入后阅读时 使用fstream
发生了一些问题。我试图写或阅读,它起作用。问题是什么?
文件内容是:
abcdefgh
ijklmnopqr
stuvw
xyz
代码是:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream ioFile;
char ch;
ioFile.open("search.txt", ios::in | ios::out);
if (!ioFile)
{
cout << "problem opening the file";
goto k270;
}
while (ioFile>>ch)
{
if (ch == 'z')
{
ioFile.seekp(((int)ioFile.tellg()));
ioFile << "x";
}
}
//cout<<ioFile.rdbuf();
ioFile.close();
k270:
system("pause");
return 0;
}
I am learning how to read and write from file . There is a problem that when I try to write (--something in the file letter for example--) after reading or read after writing in the file
using fstream
something wrong is happening. I tried to just write or read and it worked. what is the problem?
the file content is :
abcdefgh
ijklmnopqr
stuvw
xyz
and the code is :
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream ioFile;
char ch;
ioFile.open("search.txt", ios::in | ios::out);
if (!ioFile)
{
cout << "problem opening the file";
goto k270;
}
while (ioFile>>ch)
{
if (ch == 'z')
{
ioFile.seekp(((int)ioFile.tellg()));
ioFile << "x";
}
}
//cout<<ioFile.rdbuf();
ioFile.close();
k270:
system("pause");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看此答案: https://stackoverflow.com/a/117567454/11829247 它解释了您正在遇到的错误。
简短版本:输入和输出是缓冲的,并且交织的读取和写入仅在强制缓冲区之间的更新时才能工作。
这对我有用:
不同之处在于我使用
iofile.seekp(-1,std :: ios_base :: cur);
从cur> cur
租用一步。位置。您也可以使用iofile.seekp((int)iofile.tellg()-1);
- 注意-1
。然后,逐渐退缩并覆盖Z,请使用
iofile.flush();
迫使写入要归档。这也意味着更新了读取缓冲区,而没有此读取操作仅在其缓冲区中退后一步,并继续读取相同的缓冲z。Look at this answer: https://stackoverflow.com/a/17567454/11829247 it explains the error you are experiencing.
Short version: Input and output is buffered and interleaving reads and writes only work if you force buffer updates in between.
This works for me:
The difference is that I use
ioFile.seekp(-1, std::ios_base::cur);
to move one step back from thecur
rent position. You could also useioFile.seekp((int)ioFile.tellg() -1);
- note the-1
.Then after stepping back and overwriting the z, use
ioFile.flush();
to force the write to be pushed to file. This also means that the read buffer is updated, without this the read operation just steps back in its buffer and keeps reading the same buffered z.