【问题标题】:Why is fstream not working for writing files in Linux? [closed]为什么 fstream 不能在 Linux 中写入文件? [关闭]
【发布时间】:2018-12-17 23:41:07
【问题描述】:

fstream 不适用于在 Linux 中写入文件,使用以下代码:

#include <iostream>                     //for console input and output
#include <fstream>                      //for file input and output

int main(int argc, char **argv) {
    std::ofstream outFile("~/test_ws/src/data_logger/src/myFile.txt", std::ios::out | std::ios::binary);
    outFile.open("~/test_ws/src/data_logger/src/myFile.txt", std::ios::out | std::ios::binary);
    if(outFile.is_open()) {
        outFile << "Writing whether you like it or not.\n";
        std::cout << "YES!\n";
    } else std::cout << "Nope!\n";
    outFile.close();
}

有什么问题?或者,是否有其他 C++ API 可用于在 Linux 中写入文件?

【问题讨论】:

  • “fstream 不适用于在 Linux 中写入文件” 嗯,请问是什么?当然,这适用于任何平台操作系统。您的错误情况可能是您没有告诉我们的其他情况。
  • 我编辑了这个问题,而是询问为什么代码不起作用,但也让您的 XY question 完好无损。提示:对于未来的问题,通常最好不要做出假设(例如,代替“为什么 foo 函数在 bar 语言中不起作用?”,尝试“为什么我的代码使用 foo 函数不工作吗?”)。

标签: c++ linux api fstream ofstream


【解决方案1】:

fstream & co.在 Linux 上运行良好。您的代码的问题在于您使用的是 ~,这不是 C++ fstream 和一般较低级别系统调用所识别的“真实”路径,但它通常在命令行中工作,因为它被扩展由外壳

如果你想让你的程序进行类似shell的路径扩展,你可以调用wordexp函数;请注意,在多年的 Linux 工作中,我认为我不需要它,因为通常路径作为命令参数来自“外部”,已经被 shell 扩展(这是一般假设,不要被打破避免双重扩展;wordexp 在扩展路径时有其典型用法,例如在配置文件中)。

【讨论】:

  • 反对者介意解释一下吗?
  • 谢谢,现在可以使用了。我想我也不能在文件名中使用 .txt。
  • @Raisintoe: 不,.txt 很好......你有什么问题?
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多