Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ QtCreator中的相对路径_C++_Qt Creator_Ifstream - Fatal编程技术网

C++ QtCreator中的相对路径

C++ QtCreator中的相对路径,c++,qt-creator,ifstream,C++,Qt Creator,Ifstream,我正在将一个控制台程序和一个包含文件名行(相对于当前目录)的配置文件移植到Qt。在QtCreator中运行/调试GUI时,似乎无法从工作目录加载文件 假设我的文件系统如下所示: C:/MyProjectSource C:/MyProjectSource-Desktop-Debug // <-- created by QtCreator C:/MyProjectSource-Desktop-Debug/debug/MyProgram.exe // <- my program C:/My

我正在将一个控制台程序和一个包含文件名行(相对于当前目录)的配置文件移植到Qt。在QtCreator中运行/调试GUI时,似乎无法从工作目录加载文件

假设我的文件系统如下所示:

C:/MyProjectSource
C:/MyProjectSource-Desktop-Debug // <-- created by QtCreator
C:/MyProjectSource-Desktop-Debug/debug/MyProgram.exe // <- my program
C:/MyProjectSource-Desktop-Debug/debug/params.txt    // <- program's config
C:/MyProjectSource-Desktop-Debug/debug/cfg/file1.txt // <- extra file
C:/MyProjectSource-Desktop-Debug/debug/cfg/file2.txt // <- extra file
读取file1.txt的代码

std::ifstream ifs(filename); // <-- @runtime, filename = 'cfg/file1.txt'
if (!ifs)
{
    // failed inside QtCreator, but fine when start from explorer
    EMSG_OPENFILE(filename);
    exit(-1);
}

std::ifstream ifs(文件名);// 相对路径是相对于当前工作目录,而不是存储可执行文件的目录,因此需要将当前工作目录更改为可执行文件目录,只需在主功能后添加此行:

QDir::setCurrent(QCoreApplication::applicationDirPath());
如果需要从Qt Creator设置当前工作目录: 项目->运行->您将看到工作目录文本框

然后从“浏览”按钮将此路径更改为可执行位置

QDir::setCurrent(QCoreApplication::applicationDirPath());