如何在c++中使用' fstream '同时读写文件
How to read and write in file with `fstream` simultaneously in c++?
我有以下代码
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
fstream ofile;
ofile.open("test.txt", ios::in | ios::out | ios::app);
for(string line; getline(ofile, line) ; ) {
cout << line << endl;
}
ofile << "stackexchnange" << endl;
ofile.close();
return 0;
}
test.txt
包含
hello world!
stackoverflow
以上代码输出
hello world!
stackoverflow
运行代码后,stackexchange
不附加在test.txt
的末尾。如何在文件中读取和写入?
Nawaz的评论是正确的。读取循环迭代,直到fstream::operator bool
(ofile
的)返回false。因此,在循环之后,必须设置failbit或badbit。当循环尝试最后一次读取,但只剩下EOF可读时,设置failbit。这是完全可以的,但是在尝试再次使用该流之前,您必须重置错误状态标志。
// ...
ofile.clear();
ofile << "stackexchnange" << endl;
fstream有两个位置:输入和输出。在你的例子中,当你打开文件时,它们都被设置为文件的开头。
所以你有4个方法:
tellp // returns the output position indicator
seekp // sets the output position indicator
tellg // returns the input position indicator
seekg // sets the input position indicator
在您的例子中,您可以使用以下行将输出位置设置为文件
的末尾ofile.seekp(0, std::ios_base::end);
PS我错过了ios::app标志。认错。@Nawaz的评论给出了正确的答案:在阅读了整个文件之后,有必要调用
ofile.clear(); //cleanup error and eof flags
相关文章:
- 用C++快速读写文件
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 在一个读写器队列中,我可以用volatile替换原子吗
- C++套接字对不读/写父/子
- 如何调试读写器锁的死锁?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- Linux 挂载使用重新挂载以允许读写
- C++中读/写二进制文件
- 如何读/写或遍历 std::array 中的特定元素范围?
- 内存排序或读取-修改-写入操作,仅(读/写)内存顺序
- USB-HID 读/写(重叠)等待单个对象不返回C++
- 在c++中使用同一个fstream对象进行读写时,是否有任何导致错误的特性
- 如何在c++中使用' fstream '同时读写文件
- 如何在Visual Studio中打开fstream进行读写操作
- 使用fstream在c++中读写二进制文件
- 如何用C++中的fstream安全地写/读A类向量
- 打开一个fstream进行读写(二进制)
- fstream读/写移动文件指针
- Fstream二进制读/写行为