std::getline with std::fstream
std::getline with std::fstream
我正在使用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();
}
相关文章:
- 使 std::fstream 写入文件末尾,但从头开始读取
- Windows std::fstream 修改文件后打开()?
- std::fstream 在 MSVC 和 G++ 上使用 UTF-8 的不同行为
- std::getline with std::fstream
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- std::fstream 已使用,但编译器抛出错误
- std::fstream 需要很长时间才能将大数据写入.csv文件中
- STD :: FSTREAM在使用预先分配的内存时在Main之后崩溃
- STD :: FSTREAM文件处理重复使用的问题
- 使用“QUrl”作为文件路径馈送到“std::fstream”
- 为什么与cstdio和std::fstream相比,SDL_RWops在写入文件时表现如此糟糕
- 检查是否使用std :: fstream编写文件
- 为什么 std::fstream 返回 void 而不是 bool
- 正在从std::fstream检索文件描述符
- 将对象序列化为加密的 std::fstream (C++)
- 从文件读取,而另一个进程正在使用 std::fstream 写入该文件
- reusing std::fstream
- 移动是否分配了 std::fstream 关闭原始流
- C++中std::fstream::X和std::ios::X之间的差异
- 我们可以在SDL2中使用std::fstream而不是SDL_RWops吗