读取QDataStream中的特定对象并计算存储的对象数

问题描述 投票:0回答:1

我正在将一些对象写入二进制文件,我想读回它们。为了向您解释我想做的事情,我准备了一个简单的示例,其中包含User类,其中包含QString名称和QList名称的childs。请参见下面的代码。

#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或其他方法成功的提示?

c++ qt binaryfiles qdatastream
1个回答
0
投票

请在此处找到最终不需要二进制文件但在SQL db中使用BLOB的解决方案:

SOLUTION

© www.soinside.com 2019 - 2024. All rights reserved.