为什么fstream不打开文件? [关闭]

问题描述 投票:-2回答:2

我试图使用下面的代码打开一个文件。但是,它不会起作用。我在macOS Mojave 10.14上使用Xcode 10.1。

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    // "..." is meant to hide irrelevant information of the absolute file path.
    string filename = "Macintosh HD/Users/.../input.txt";
    ifstream inFile(filename);
    cout << inFile.is_open() << endl;
}

代码打印0。我是C ++的新手..任何人都可以告诉我代码中有什么问题?谢谢!

c++ xcode macos io fstream
2个回答
1
投票

许多人建议,文件路径不正确,代码是正确的。错误是我从右键单击文件的Get Info选项复制了绝对文件路径。非常奇怪 - 文件路径字符串在外观上似乎是正确的,但事实并非如此。不知道为什么。对于谁在乎,使用Copy (filename) as Pathname选项进行复制是正确的。


0
投票

我觉得这不太可能是你文件的正确途径。摆脱“Macintosh HD”部分,它可能会工作。

你的评论后,我这样做了:

$ g++ Foo.cpp -o Foo
$ Foo
1
$ cat Foo.cpp
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string filename = "/Users/jpl/foo.cpp";
    ifstream inFile(filename);
    cout << inFile.is_open() << endl;
}

你文件名中真的没有...,是吗?

我也删除了整个路径(filename =“foo.cpp”;),它也打印出1。

您是从IDE还是命令行运行它?您的文件是否真的在您认为的位置,您的IDE是否使用您认为它真正使用的路径运行程序?

© www.soinside.com 2019 - 2024. All rights reserved.