c++ - 为什么我的C++程序只能读取绝对目录而不能读取同一文件夹中的文件?

标签 c++ io ifstream absolute-path

我使用 VS2012 编写了一个小的 VC++ 程序并尝试读取一个文本文件。我将文件放在发布文件夹中。但是,在使用绝对文件目录之前我无法读取文件。我在网上找不到有用的信息。代码是这样的

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

using namespace std;

int main()
{
    cout<<"Hello World!"<<endl;
    string test;
    ifstream myfile;
    myfile.open("E:\\Glus\\Project2\\Release\\bunny.txt");
    if(myfile.is_open())
    {
        string s0,s1;
        int x0, x1;
        myfile>>s0>>x0;
        cout<<s0<<x0<<endl;
        myfile>>s1>>x1;
        cout<<s1<<x1<<endl;
    }
    else
    {
        cout<<"Error in reading file!"<<endl;
    }
    myfile.close();
    cin>>test;
    return 0;
}

谢谢!

最佳答案

路径不是相对于可执行文件,而是相对于当前目录(参见 _getcwd )。

如果您是从 VC 启动应用程序,请尝试

"..\\Release\\bunny.txt"

对于实际应用程序,我建议检测可执行文件的路径并使用它来构建数据文件的路径。更可靠、更安全。

关于c++ - 为什么我的C++程序只能读取绝对目录而不能读取同一文件夹中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208004/

相关文章:

c++ - new(std::nothrow) int[n] 抛出异常

php - 使用 PHP 在 Linux 服务器上运行 C++ 可执行文件

c++ - 这两个比较表达式是否相同?

io - 程序只打印输入文件的最后一个字符串

Java:使用文本文件

c++ - 到达文件末尾后倒回 ifstream 对象

c++ - 使用 "ifstream"时出现段错误

c++ - 可以将静态 constexpr 变量用作模板参数吗

c# - FileStream.Dispose 是否立即关闭文件?

c++ - 试图输出 exe 文件中的所有内容