C++ 没有使用 fstream 将输出发送到文件
C++ No output sent to file using fstream
我有这段代码,它使用 fstream 来读取和写入文件。fstream 对象被保存为对象的成员,并在构造函数中初始化,如下所示:
idmap.open(path, std::fstream::in | std::fstream::out | std::fstream::app);
如果文件尚不存在,则会正确创建该文件。然后它被写成这样:
idmap.seekp(0, std::fstream::end);
idmap << str.size() << ':' << str << 'n';
idmap.flush();
idmap.sync();
它应该这样阅读,但我不知道它是否有效,因为该文件一直是空的:
idmap.seekg(0);
while (!idmap.eof()) {
idmap.getline(line, 1024);
idtype id = getIDMapEntry(std::string(line));
if (identifier.compare(nfile.getIdentifier()) == 0) {
return nfile;
}
}
然后在程序退出时关闭:
idmap.close();
这可能是程序中的其他内容,但我想我会在这里问,以防我做了一些愚蠢的事情,并并行挖掘其他所有内容。
对我有用。
除.eof()
错误外,该程序完全按预期工作:
#include <fstream>
#include <iostream>
int main() {
std::fstream idmap;
const char path[] = "/tmp/foo.txt";
idmap.open(path, std::fstream::in | std::fstream::out | std::fstream::app);
std::string str("She's no fun, she fell right over.");
idmap.seekp(0, std::fstream::end);
idmap << str.size() << ':' << str << 'n';
idmap.flush();
idmap.sync();
idmap.seekg(0);
#if 1
// As the user presented, with .eof() bug
char line[1024];
while (!idmap.eof())
{
idmap.getline(line, 1024);
std::cout << line << "n";
}
#else
// With fix for presumably unrelated .eof() bug
std::string line;
while(std::getline(idmap, line)) {
std::cout << line << "n";
}
#endif
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词