“Path issues when opening a QFile” 的中文翻译是:打开 QFile 时的路径问题。

huangapple go评论144阅读模式
英文:

Path issues when opening a QFile

问题

在以下代码中,我有一个关于文件路径的问题:

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);

以"file://"开头的路径在QFile::open中无法识别:

QIODevice::read (QFile, "file:///home/pietrom/default.json"): 设备未打开

问题在于我从QML FileDialog中获取了这种格式。

我应该只是从路径中去掉"file://"标记,还是有一种正确的方法来修复这个问题?

英文:

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?

答案1

得分: 1

你可以使用 QUrl::toLocalPath (这里) 来获取正常的路径

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" ;
}
英文:

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

 QString fileName;
    fileName = &quot;/home/pietrom/default.json&quot;;          // ok
    fileName = &quot;file:///home/pietrom/default.json&quot;;   // should be OK as well

    QFile jsonFile;
    QUrl url(fileName);
    jsonFile.setFileName(url.toLocalFile());
    bool ok = jsonFile.open(QIODevice::ReadOnly);
    if (!ok){
            qDebug() &lt;&lt; &quot;Failed &quot; &lt;&lt;  jsonFile.errorString() &lt;&lt; &quot;  &quot; &lt;&lt; jsonFile.fileName();
    }
    else
    {
            qDebug() &lt;&lt; &quot;OK&quot; ;

    }

huangapple
  • 本文由 发表于 2023年6月1日 00:30:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定