How to concatenate an absolute path and relative path with QDir?
Asked Answered
W

2

26

I have a relative path and absolute path that look something like this:

Absolute: /tmp/somedir
Relative: anotherdir/file.txt

I would like to concatenate the two (/tmp/somedir/anotherdir/file.txt) with QDir but I am not quite sure what the proper way of doing that is.

According to the documentation for QDir::absoluteFilePath:

"Returns the absolute path name of a file in the directory."

This would be ideal if all I had was a filename, but I have a relative path as well. I looked at some of the other functions on the page, but none of them seemed to be what I was looking for.

What function should I be using?

Wayne answered 28/7, 2012 at 2:40 Comment(0)
D
38

I think you are looking for filePath().

QString finalPath = QDir("/tmp/somedir").filePath("anotherdir/file.txt");
Domenic answered 29/7, 2012 at 2:55 Comment(0)
G
1

Small addition if the relative file path starts with a dot:

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;

Output:

incorrect path: "/tmp/somedir/./anotherdir/file.txt"
correct path: "/tmp/somedir/anotherdir/file.txt"
Genista answered 4/5, 2021 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.