原文: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等其他数据存储结构