【发布时间】:2017-01-10 00:42:00
【问题描述】:
我终于找到了一个 QFile 可以接受的路径文件,使用 QFile.exist() 和健康的试验和错误剂量。
我想知道为什么以下工作:
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
QString path = QDir::currentPath(); // Get current dir
path.append("/noteLibrary.json");
QFile file(path); // Give QFile current dir + path to file
if (!file.exists()) { // Check to see if QFile found the file at given file_path
qDebug() << "NO FILE HERE";
}
qDebug() << path; // See what path was finally successful
file.open(QIODevice::ReadOnly); // Continue parsing document to confirm everything else is functioning normally.
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
qDebug() << json["die"].toString(); // Should output "280C4"
成功输出:
"/home/pi/noteLibrary.json"
"280C4"
但以下方法不起作用:
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
QFile file("/home/pi/noteLibrary.json"); // Give QFile current dir + path to file
if (!file.exists()) { // Check to see if QFile found the file at given file_path
qDebug() << "NO FILE HERE";
}
//qDebug() << path; // See what path was finally successful
file.open(QIODevice::ReadOnly); // Continue parsing document to confirm everything else is functioning normally.
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
qDebug() << json["die"].toString(); // Should output "280C4"
错误输出:
NO FILE HERE
QIODevice::read (QFile, "/home/pi/Desktop/noteLibrary.json"): device not open
""
为什么 QFile 会以不同的方式对待这些?这是 QString 格式问题吗?还是我将其远程部署到 Raspberry Pi 3 的事实可能是罪魁祸首?
【问题讨论】:
-
第二段代码不能做这个输出因为
path变量没有在那里声明。此外,您提供给QFile的真实路径是/home/pi/Desktop/noteLibrary.json,而不是/home/pi/noteLibrary.json。请检查一下。 -
哇。我必须复制/粘贴最近 8 次尝试之一的错误输出才能完成这项工作。很抱歉在此浪费您的时间。