如何使用QDir连接绝对路径和相对路径?

26

我有一个相对路径和绝对路径,看起来像这样:

绝对路径:/tmp/somedir
相对路径:anotherdir/file.txt

我想使用QDir将它们连接起来(/tmp/somedir/anotherdir/file.txt),但我不太确定正确的方法是什么。

根据QDir::absoluteFilePath的文档:

"返回目录中文件的绝对路径名。"

如果我只有文件名,那么这很理想,但我也有相对路径。我查看了页面上的其他一些函数,但似乎没有符合我要求的。

我应该使用哪个函数?

2个回答

38

我认为你正在寻找filePath()

QString finalPath = QDir("/tmp/somedir").filePath("anotherdir/file.txt");

0

如果相对文件路径以点号开头,则需要进行小的修改:

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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接