Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[Solved] Howto get the path part of a filename?



  • I have a (relative) filename for a file that doesn't yet exist.

    Before I can create it, I have to make sure all the parent directories exist. QDir::mkpath should do that for me.

    However, I cannot simply hand over the filename to mkpath. Instead, I have to hand over the path part of the filename, e.g. for 'home/test/mytest.png' the path part would be 'home/test'

    Yet, I haven't found any method in QDir, QFile or QFileInfo that would return the path part from a either relative or absolute filename. Nor have I found a function that would allow me to remove the last level from a path/filename. Of course, I can resort to string manipulation, but I feel there should be something more path-aware doing that.

    Have I missed something?

    (Qt 4.8)


  • Moderators

    You missed QFileInfo::absolutePath() and QFileInfo::canonicalPath()



  • For a non-existing file?

    Edit: I was fooled into thinking that QFileInfo would require the file to exist.


  • Moderators

    Well according to the doc cannonicalPath() indeed returns empty string if the file doesn't exist but you should be fine with absolutePath()


Log in to reply