原文:http://beself.top/2020/02/14/qt-read-write-binaryfiledata-struct/
二進制文件存儲方式比較方便,文本小,保密效果好
- 定義一個數據結構並實現相關操作
- 使用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;
}
注
- 其中QList可以換成QVector等其他數據存儲結構