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

Getting the directory from a path



  • I have a path like this:

    C:/ProgramData/XM Editor/RnD/data/2018-07-01/defaultprog 2018-07-01 14h 53m.csv
    

    I only want this:

    C:/ProgramData/XM Editor/RnD/data/2018-07-01
    

    I can get the filename on its own, but I cannot find a simple way to get the directory name only. I don't want to use string processing that is not cross platform. So far I have looked at these objects:

    QDir
    QUrl
    QFileInfo
    

    I have tried numerous functions and they all return either just the filename or the entire path including the filename. There has to be a simple way to do this that I am overlooking.


  • Lifetime Qt Champion

    Hi
    What about
    https://doc.qt.io/qt-5/qfileinfo.html#absolutePath
    "Returns a file's path absolute path. This doesn't include the file name."



  • Well this is kinda hackish:

        QString csv_filename; // set somewhere else
        QString basename = QUrl(csv_filename).fileName();
        QString basepath = csv_filename.remove(basename);
    

    This seems to work and I need both parts.


  • Lifetime Qt Champion

    Hi

     QFileInfo fi("e:/folder name/file name with space.txt");
     qDebug() << fi.absolutePath() << " fn=" << fi.fileName();
    

    gives
    "E:/folder name" fn= "file name with space.txt"

    Did i miss something ?



  • @fcarney
    What happens if your basename occurs not only at the end but also somewhere in the middle?

    /something/basename/somethingelse/basename
    

    What is wrong with the QFileInfo methods @mrjj suggested which do just what you want? [He's just posted exactly what you need.]



  • @mrjj said in Getting the directory from a path:

    Hi

     QFileInfo fi("e:/folder name/file name with space.txt");
     qDebug() << fi.absolutePath() << " fn=" << fi.fileName();
    

    gives
    "E:/folder name" fn= "file name with space.txt"

    Did i miss something ?

    Heh, no you didnt miss anything. I just posted at nearly the same time as you so I didnt see the update to the thread. Thanks


Log in to reply