Qt-讀寫二進制文件(數據結構)

原文:http://beself.top/2020/02/14/qt-read-write-binaryfiledata-struct/
二進制文件存儲方式比較方便,文本小,保密效果好

  1. 定義一個數據結構並實現相關操作
  2. 使用QDataStream進行讀寫操做

數據結構

#include <QtCore>

struct AccountInfo
{
// 數據
    QString Account;
    QString LogPasswd;

// 初始化
    AccountInfo(){}
    AccountInfo(const QString &account,
                const QString &logPasswd) :
        Account(account),
        LogPasswd(logPasswd){}
    bool operator==(const AccountInfo &other) const
    {
        return Account == other.Account && LogPasswd == other.LogPasswd;
    }
};

// 符號重載
inline QDataStream &operator<<(QDataStream &stream, const AccountInfo &Info)
{
    return stream << Info.Account << Info.LogPasswd;
}

inline QDataStream &operator>>(QDataStream &stream, AccountInfo &Info)
{
    return stream >> Info.Account << Info.LogPasswd;
}

寫文件

    QList<AccountInfo> Info;
    Info.push_back(AccountInfo("1111111111", "11111111111111111111111"));
    Info.push_back(AccountInfo("2222222222", "22222222222222222222222"));
    Info.push_back(AccountInfo("3333333333", "33333333333333333333333"));
    QFile file("AccountInfo.dat");
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "open file failed.";
        return;
    }
    QDataStream out(&file);
    out << Info;
    file.close();

讀文件

    QFile file("AccountInfo.dat");
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "open file failed.";
        return;
    }
    QList<AccountInfo> Info;
    QDataStream in(&file);
    in >> Info;
    file.close();
    for(const auto& d : qAsConst(Info)){
        qDebug() << "Account:" << d.Account << "Passwd:" << d.LogPasswd;
    }

  1. 其中QList可以換成QVector等其他數據存儲結構
發佈了29 篇原創文章 · 獲贊 13 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章