C++ 文件 I/O - 无法同时读取/写入?
C++ File I/O--can't read/write simultaneously?
我正在写一些简单的代码,应该每隔一个字符读取一次,并用"?"覆盖它们相邻的字符s在一个随机文本文件中。例如。test.txt包含"Hello World";运行程序后,它将是"H?l?o?W?r?d"
下面的代码允许我从控制台窗口的文本文件中读取其他字符,但在程序结束后,当我打开test.txt时,什么都没有改变。需要帮助找出原因。。。
#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;
}
您忘记考虑您有两个流,istream
和ostream
。
您需要同步这两个流的位置以实现您想要的内容。我修改了你的代码,以表明我的意思。
#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
}
您滥用了eof()
。改为这样做:
#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
char ch;
while (data.get(ch))
{
cout << "ch is now " << ch << endl;
data.put('?');
}
data.close();
return 0;
}
相关文章:
- 如何在C++中从文件中读取/写入多个对象
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 用 C++20 的给定键读取/写入 std::multimap 的所有值?
- 从缓冲区读取/写入文件
- 如何运行外部程序,向其传递内存地址以读取/写入?
- C++11 原子<>:只能使用提供的方法读取/写入?
- 从QDataStream读取/写入QT
- 在Windows上读取/写入未格式化的SD卡
- 尝试读取/写入Graphviz DAG值的工作证明会导致segfault
- 在 c++ 中读取/写入文件
- 在 c++ 中向/从文件中读取写入变量
- 如何在 c++ 中读取/写入无符号数组到 ifstream/ostream?
- QTcpSocket 或 QSslSocket 是否会自动创建用于读取/写入的线程?
- 使用来自 C 的内存地址的 Julia 读取/写入结构数据
- C++ 如何使用相同的类和方法来读取/写入可变大小的数据
- 在 Cap'nProto 中读取/写入配置结构
- 在另一个线程中读取/写入信息
- 提升信息解析器在读取/写入 INFO 格式文件时删除所有注释
- 在常量引用获取器上读取写入互斥锁(使用 Qt)
- C 读取/写入两个不同的文件(需要帮助了解要使用的语法)