c++ - fstream open() Mac OS X 中的相对路径不起作用

标签 c++ macos file fstream ofstream

<分区>

fstream 的 open() 是采用相对文件路径还是绝对文件路径?这是示例代码 -

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main() {
    fstream myfile;

    myfile.open("subd/example.txt");
    if(myfile.is_open()) {
            for(int i = 0; i < 10; i++) {
                    myfile << "Example data " << i << endl;
            }
    } else cout << "Unable to open " << endl;
    myfile.close();
    return 0;
}

我在 MAC OS X 环境中工作。子目录已经存在。 .open() 对每种情况都返回 false。我也在使用 -std=c++11。我该如何解决这个问题? “subd”目录的权限是:

enter image description here

输出总是“无法打开”。 原始帖子(此帖子被标记为重复的帖子)的解决方案没有解决我的问题。

Solution, because none of the responses below completely resolve my issue

Use ofstream with the relative path(with respect to the location of the program executable ie. argv[0]). fstream just doesn't seem to work the same way.

最佳答案

Does fstream's open() take relative or absolute file paths?

是的。

如果是相对的,那么它是相对于调用环境的 current working directory .

请注意,这可能不是您的源代码在磁盘上的位置。

关于c++ - fstream open() Mac OS X 中的相对路径不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36008067/

相关文章:

c++ - 将输出重定向到文件并询问用户输入

C++,将自定义占位符与函数参数匹配

html - 字体在 Mac 上不显示

node.js - Node 已经安装,只是没有链接

java - calabash-android 给出 JAVA_HOME 错误

c++ - 从同一目录读取图像?

c++ - unique_ptr 的段错误

python - 将数据从 Python 程序发送到 C++ 程序的策略

ios - 在 iOS 上删除文件夹中的所有文件

android - 使用字符串删除SD卡android中的文件