std::getline with std::fstream

std::getline with std::fstream

本文关键字:std fstream getline with      更新时间:2023-10-16

我正在使用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 循环,说明读取失败。

我怎样才能克服这个问题?

您忘记重新打开流。实际上,您无法(同时(在两个方向上打开流。
所以步骤是:

  • 打开流进行写入
  • 写入数据
  • 关闭流
  • 重新打开流进行阅读
  • 读取数据
  • 关闭它(可选(

您的示例可以重写为:

#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;
}

请注意,在尝试使用流之前,最好先检查流是否已成功打开。

我将尝试解释这个问题。

语句std::fstream* fs = new std::fstream("xx.txt");如果文件以默认模式"in|out"存在,则将打开文件。 如果该文件不存在,则从构造函数 std::fstream 内部打开的调用将失败。这可以通过使用函数 failure(( 检查故障位来检查。因此,您将明确需要调用"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 performedn";
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();
}