我有一个相对路径和绝对路径,看起来像这样:
绝对路径:/tmp/somedir 相对路径:anotherdir/file.txt
我想使用QDir将它们连接起来(/tmp/somedir/anotherdir/file.txt
),但我不太确定正确的方法是什么。
根据QDir::absoluteFilePath
的文档:
"返回目录中文件的绝对路径名。"
如果我只有文件名,那么这很理想,但我也有相对路径。我查看了页面上的其他一些函数,但似乎没有符合我要求的。
我应该使用哪个函数?
我有一个相对路径和绝对路径,看起来像这样:
绝对路径:/tmp/somedir 相对路径:anotherdir/file.txt
我想使用QDir将它们连接起来(/tmp/somedir/anotherdir/file.txt
),但我不太确定正确的方法是什么。
根据QDir::absoluteFilePath
的文档:
"返回目录中文件的绝对路径名。"
如果我只有文件名,那么这很理想,但我也有相对路径。我查看了页面上的其他一些函数,但似乎没有符合我要求的。
我应该使用哪个函数?
我认为你正在寻找filePath()
。
QString finalPath = QDir("/tmp/somedir").filePath("anotherdir/file.txt");
如果相对文件路径以点号开头,则需要进行小的修改:
QString absoluteDirPath = "/tmp/somedir";
QString relativeFilePath = "./anotherdir/file.txt";
QString incorrectPath = QDir{absoluteDirPath}.filePath(relativeFilePath);
qDebug() << "incorrect path:" << incorrectPath;
QString correctPath = QFileInfo{incorrectPath}.absoluteFilePath(); // removes the .
qDebug() << "correct path:" << correctPath;
输出:
incorrect path: "/tmp/somedir/./anotherdir/file.txt"
correct path: "/tmp/somedir/anotherdir/file.txt"