qtpathqfileqiodevice

Path issues when opening a QFile


In the following code I have an issue with file paths:

std::string fileName;
fileName = "/home/pietrom/default.json";          // ok
fileName = "file:///home/pietrom/default.json";   // error

QFile jsonFile;
jsonFile.setFileName(fileName.c_str());
jsonFile.open(QIODevice::ReadOnly);

A path starting with "file://" is not recognized by QFile::open:

QIODevice::read (QFile, "file:///home/pietrom/default.json"): device not open

The problem is that I get that format from a QML FileDialog.

Shall I just cut the "file://" token from the path, or is there a proper way to fix this?


Solution

  • You could use QUrl::toLocalPath (here) to get the normal path

     QString fileName;
        fileName = "/home/pietrom/default.json";          // ok
        fileName = "file:///home/pietrom/default.json";   // should be OK as well
    
        QFile jsonFile;
        QUrl url(fileName);
        jsonFile.setFileName(url.toLocalFile());
        bool ok = jsonFile.open(QIODevice::ReadOnly);
        if (!ok){
                qDebug() << "Failed " <<  jsonFile.errorString() << "  " << jsonFile.fileName();
        }
        else
        {
                qDebug() << "OK" ;
    
        }