C ++文件I / O - 不能同时读/写? [英] C++ File I/O--can't read/write simultaneously?
问题描述
例如。
test.txt包含Hello World;
在运行程序后,它会是H?l?o?W?r?d?
我的代码可以让我读到其他所有的字符从控制台窗口中的文本文件,但程序结束后,当我打开test.txt,没有什么改变。需要帮助找出原因...
#include< iostream>
#include< fstream>
使用namespace std;
int main()
{
fstream data(test.txt,ios :: in | ios :: out); //这里test.txt可以是任意的随机文本文件
while(!data.eof())
{
if(!data.eof())
{
char ch;
data.get(ch);
cout<< ch现在是<< ch< ENDL;
$ b if(!data.eof())
data.put('?');
}
data.close();
返回0;
你忘了考虑你有2个流, istream
和 ostream
。
您需要同步这两个流的位置来实现你想要的。我修改了你的代码以显示我的意思。
#include< iostream>
#include< fstream>
使用namespace std;
int main()
{
char ch;
fstream data(test.txt,ios :: in | ios :: out); //这里test.txt可以是任何随机文本文件
while(data.get(ch))
{
cout<< ch现在是<< ch< ENDL;
data.seekg(data.tellp()); //设置ostream指向istream设置的新位置
data.put('?');
data.seekp(data.tellg()); //设置istream指向新的位置,ostream set
}
data.close(); //不需要,因为它是fstream ::〜fstream()的一部分
return 0; //不需要,因为默认情况下返回0
code $ $ $ $ $ $ $ $ $I'm writing some simple code that's supposed to read every other character, as well as overwriting their adjacent characters with '?'s in a random text file.
eg.
test.txt contains "Hello World";
after running the program, it'd be "H?l?o?W?r?d"
My code below allows me to read every other character from the text file in the console window, but after the program ends and when I open up test.txt, nothing has been changed. Need help to figure out why...
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (!data.eof())
{
if (!data.eof())
{
char ch;
data.get(ch);
cout << "ch is now " << ch << endl;
}
if (!data.eof())
data.put('?');
}
data.close();
return 0;
}
解决方案 You forgot to consider that you have 2 streams, istream
and ostream
.
You need to synchronize the location of these 2 streams to achieve what you want. I modified your code a bit to show what I mean.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char ch;
fstream data("test.txt", ios::in | ios::out); //here the test.txt can be any random text file
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.seekg(data.tellp()); //set ostream to point to the new location that istream set
data.put('?');
data.seekp(data.tellg()); //set istream to point to the new location that ostream set
}
data.close(); // not required, as it's part of `fstream::~fstream()`
return 0; // not required, as 0 is returned by default
}
这篇关于C ++文件I / O - 不能同时读/写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!