我编写了一个简单的代码来使用Qt5的QFile打开纯文本文件,如下所示;
// main.cpp
#include <iostream>
using std::endl;
using std::cout;
#include <QCoreApplication>
#include <QFile>
#include <QIODevice>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile plainFile("plain.txt");
if(plainFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
cout << "File opened successfull" << endl;
plainFile.close();
}
else{
cout << "could not open file." << endl;
}
return a.exec();
}编译和运行时的输出是“无法打开文件”。我做错什么了?
发布于 2013-08-10 06:59:11
可能是因为plain.txt不存在于当前工作目录或路径中。确保文件位于工作目录中,或者将绝对路径传递给QFile。
还可以查看QFile::exists返回的内容。
发布于 2013-08-10 07:19:56
韦特·惠森格鲁特是对的。
请记住,默认情况下,当您从QtCreator工作目录运行应用程序时,例如,C:\Projects\build-Test-Desktop_Qt_5_1_0_MinGW_32bit-Debug。但是您的.exe文件位于C:\Projects\build-Test-Desktop_Qt_5_1_0_MinGW_32bit-Debug\Debug中。
当您直接运行您的.exe时,工作目录将是该文件夹,该文件现在被放置在该文件夹中。
所以,你可以:
1.通过绝对路径。
2.将文件放在当前的工作目录中(我认为这是最好的解决方案)。
3.改变相对路径:QFile plainFile("debug/plain.txt");
https://stackoverflow.com/questions/18159448
复制相似问题