我正在使用std::fstream
读取和写入同一文件。我可以看到正在发生写入,但看不到正在读取。
在网络上搜索后,我知道不能同时在和应用程序模式下进行设置。因此,摆脱了这一点,并使不传递任何参数变得非常简单。
我很想知道未读的原因。
另外,人们如何使用相同的fstream读取和写入相同的文件?
我的代码:
#include<iostream>
#include<fstream>
int main() {
std::fstream* fs = new std::fstream("xx.txt");
*fs << "Hello" << std::endl;
(*fs).close(); // ?
std::string line;
while(std::getline(*fs, line)) {
std::cout << line << std::endl;
}
}
使用此代码,我可以xx.txt包含“ Hello”作为其内容,但是它根本不会进入while循环,表明读取失败。
我该如何克服?
答案 0 :(得分:1)
您忘记重新打开流。实际上,您不能同时打开两个方向的视频流。
因此,步骤如下:
您的示例可以重写为:
#include <fstream>
#include <iostream>
int main()
{
const std::string file_path("xx.txt");
std::fstream fs(file_path, std::fstream::app);
if(fs) // Check if the opening has not failed
{
fs << "Hello" << std::endl;
fs.close();
}
fs.open(file_path, std::fstream::in);
if(fs) // Check if the opening has not failed
{
std::string line;
while(std::getline(fs, line))
{
std::cout << line << std::endl;
}
fs.close();
}
return 0;
}
请注意,在尝试使用流之前,先检查流是否已成功打开是个好主意。
答案 1 :(得分:1)
我将尽力解释这个问题。
如果声明std::fstream* fs = new std::fstream("xx.txt");
以默认模式“ in | out”存在,它将打开文件。
如果文件不存在,则从构造函数std :: fstream内部打开的调用将失败。这可以通过使用函数fail()检查故障位来检查。因此,您将明确需要调用“ open”以将fstream对象用于数据输入。注意:除非您调用“关闭”,否则不会创建新文件。
您可以通过实际尝试打开现有文件或新文件来进行测试,以查看区别。
因此,您应该始终调用“打开”,这在两种情况下都可以使用(如果文件存在或不存在)。
#include<iostream>
#include<fstream>
int main() {
//std::fstream fs("xx.txt");
//std::cout << fs.fail() << std::endl; // print if file open failed or passed
std::fstream fs;
fs.open("xx.txt", std::fstream::in | std::fstream::out | std::fstream::app);
std::cout << fs.fail() << std::endl;
fs << "Hello" << std::endl;
if (fs.is_open())
{
std::cout << "Operation successfully performed\n";
fs.close();
}
else
{
std::cout << "Error opening file";
}
要读取文件的内容,您首先需要关闭文件。然后重新打开并阅读。据我了解,一旦开始使用对象fs进行插入,除非您明确将其关闭并重新打开,否则您将无法读取它。
fs.open("xx.txt", std::fstream::in | std::fstream::out);
std::string line;
while(std::getline(fs, line)) {
std::cout << line << std::endl;
}
std::cout << "end" << std::endl;
fs.close();
}