我正在二进制文件中写入一些对象,我想读回它们。为了向您解释我要做什么,我准备了一个简单的示例,其中包含一个包含儿童的 QString 名称和 QList 名称的类 User。请看下面的代码。
#include "QString"
#include "QFile"
#include "QDataStream"
#include "qdebug.h"
class User
{
protected:
QString name;
QList<QString> childrens;
public:
QString getName(){ return name;}
QList<QString> getChildrens(){ return childrens;}
void setName(QString x) {name = x;}
void setChildrens(QList<QString> x) {childrens = x;}
//I have no idea of how to get the number of users in "test.db"
int countDatabase()
{
}
//I would like to read the user named "pn" without putting all users in memory
void read(QString pn)
{
QFile fileRead("test.db");
if (!fileRead.open(QIODevice::ReadOnly)) {
qDebug() << "Cannot open file for writing: test.db";
return;
}
QDataStream in(&fileRead);
in.setVersion(QDataStream::Qt_5_14);
in>>*this;
}
void write()
{
QFile file("test.db");
if (!file.open(QIODevice::WriteOnly | QIODevice::Append)) {
qDebug() << "Cannot open file for writing: test.db";
return;
}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_5_14);
out<<*this;
}
friend QDataStream &operator<<(QDataStream &out, const User &t)
{
out << t.name << t.childrens;
return out;
}
friend QDataStream &operator>>(QDataStream &in, User &t)
{
QString inname;
QList<QString> inchildrens;
in >> inname >> inchildrens;
t.name = inname;
t.childrens = inchildrens;
return in;
}
};
////////////////////////////////////////////////////////////////
int main()
{
User u;
u.setName("Georges");
u.setChildrens(QList<QString>()<<"Jeanne"<<"Jean");
u.write();
User v;
u.setName("Alex");
u.setChildrens(QList<QString>()<<"Matthew");
u.write();
User w;
w.setName("Mario"); // no children
w.write();
User to_read;
to_read.read("Alex");
qDebug()<<to_read.getName();
return 0;
}
我成功地在我的二进制文件中写入了我想要的所有用户。但是,我希望能够在不将所有内容加载到内存的情况下:
- 要知道二进制文件中存储了多少用户,
- 通过给出该用户的名称来读取该用户。
到目前为止,我一直使用 QDataStream 并且我正在重载 << 和 >> 操作符以进行序列化。也许我想要的这种方法是不可能的。您能否为我提供一些使用 QDataStream 或其他方法取得成功的提示?