英文:
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 = "/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" ;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论