为什么fstream不能在Linux中编写文件?

Rai*_*toe -2 c++ linux api fstream ofstream

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();
}
Run Code Online (Sandbox Code Playgroud)

问题是什么?或者,我可以使用另一个C++ API在Linux中编写文件吗?

Mat*_*lia 7

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

如果您希望程序执行类似shell的路径扩展,可以调用该wordexp函数; 请注意,在多年从事Linux工作的过程中,我认为我从未需要这样做,因为通常路径来自"外部"作为命令参数,已经由shell扩展(这是一般的假设,不要被打破避免双重扩展的东西; wordexp在扩展路径时有其典型用法,例如在配置文件中).

  • downvoter会介意解释吗? (2认同)