使用fstream在读取后写入
writing after reading using fstream
我的印象是c++中的fstream
对象可以用于读取和写入,使用相同的流。我已经成功地能够首先写入流,然后从中读取。但是,如果我尝试再次写入该文件,则该文件不受影响。
int main()
{
std::string path="file.txt";
std::fstream fs(path.c_str());
int buffSize=100;
int bytesRead=0;
char* buffer=new char[buffSize];
fs.write("hello", 5);
fs.seekp(0, std::ios::beg);
fs.read(buffer, buffSize);
bytesRead=fs.gcount();
for(int i=0;i<bytesRead;i++) {std::cout << buffer[i];}
std::cout << "n";
fs.clear();
fs.seekp(1, std::ios::beg);
fs.write("E", 1);
std::cout << "fail: " << fs.fail() << "n";
delete[] buffer;
}
"file.txt"的初始内容只有:
AAAAAAA
程序输出:
helloAA
fail: 0
运行程序后在文本编辑器中查看该文件,可以看到最终的内容是:
helloAA
最后写的"E"没有生效,为什么会这样,我该如何解决?
编辑:我尝试使用fs.clear()
之前再次写入用户0x499602D2建议。还添加了一行打印是否设置了failbit或badbit,并更新了程序输出。最终的文件内容保持不变,但是问题仍然存在。
(更详细的答案来自我在评论中发布的问题)
你需要调用flush()
对输出流对象(从ostream派生),以便数据实际写入输出流。关于flush()
的更多信息可在此c++参考页面获得。
此操作适用于GCC 4.9.0和VS2013。
指出:
- seekg用于移动读指针
- seekp用于移动写指针
fs.seekp(0, std::ios::beg);
行中的。没有问题,因为读指针没有移动(在此之前没有读)。
代码:#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
std::string path = "H:\save.txt";
int buffSize = 100;
int bytesRead = 0;
char* buffer = new char[buffSize];
std::fstream fs(path.c_str());
fs.write("hello", 5);
fs.flush(); // flushing to disk file
fs.seekg(0, std::ios_base::beg); // moving the read pointer
fs.read(buffer, buffSize);
bytesRead = fs.gcount();
for (int i = 0; i < bytesRead; i++) {
std::cout << buffer[i];
}
std::cout << "n";
fs.clear();
fs.seekp(1, std::ios::beg);
fs.write("E", 1);
fs.flush(); // flushing to disk file
std::cout << "fail: " << fs.fail() << "n";
delete[] buffer;
return 0;
}
string data="";
string Newdata="New Data";
std::fstream output_file(fileName, ios::in| ios::out);
output_file >> data; //read Data
output_file.seekg( 0, ios::beg );//set point to zero
output_file<<Newdata<<"n"; //write new Data
output_file.close();
一旦你使用fstream读取文件,告诉<读取指针>并告诉<写指针>指向-1。为了能够再次使用fstream写入,只需调用fstream.clear(),它会将读写指针重置到读取前的位置。写指针>读取指针>
上面发布的解决方案都不起作用,但fstream.clear()有效。
相关文章:
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何使用单个fstream创建、读取和写入文件
- 如何在 c++ 中使用 fstream 读取.txt文件
- 在链表上写入和读取 fstream 的函数
- 使用 fstream 读取 csv,并且只阅读 fstream
- FSTREAM的问题读取确定,但不编写用户输入字符串
- C++ fstream 不会读取整个文件
- Fstream 在点击 EOF 时读取行为
- 如何在 c++ 中同时使用 'fstream' 写入和读取文件
- 使用fstream用中文/日文编写的文本,无法正确读取文件
- 使用 fstream 读取文件后,我无法立即写入文件
- 无法使用 fstream 从二进制文件中读取字符串,而是显示奇怪的符号
- 如果在类 temlpate 中使用,fstream 是否会在编译时通过读取和写入来访问 hardrive?
- C 从文件中读取FSTREAM数据不会返回正确的值.inputfile.tellg返回-1
- 无法使用 fstream 和 ifstream 读取 NDK C++中的文件
- CMD窗口停止工作,文本文件使用fstream读取错误
- 使用fstream从二进制文件中读取并将结果存储在向量中
- 从 fstream 中读取后,为什么它似乎需要在写入之前清除它的好位
- 从文件中读取一行并将其放入字符串中(使用 fstream)
- 读取,操纵和写入C 文档,主要使用FSTREAM和数组