我使用 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/