quint32转化为qstring_Qt: 读写二进制文件(写对象, 原始数据等)

本文介绍了如何在Qt中利用QDataStream类进行二进制文件的读写操作,包括自定义类型C的序列化与反序列化。示例展示了从文件读取和写入quint32、QMap及自定义对象C的过程,并提供了文件复制的简单实现。

#include#include#include#include#includeclassC {public:

C(quint32 value=0) :

value(value) {

}//Override operator <>.friend QDataStream&operator<

friend QDataStream&operator>>(QDataStream&in, C&obj);

quint32 getValue()const{returnvalue;

}private:

quint32 value;

};

QDataStream&operator<

out<

}

QDataStream&operator>>(QDataStream&in, C&obj) {

in>>obj.value;returnin;

}/*** Copy a file*/bool copy(constQString&source,constQString&dest) {

QFile sourceFile(source);if(!sourceFile.open(QIODevice::ReadOnly)) {

#ifdef DEBUG

std::cerr<

#endifreturnfalse;

}

QFile destFile(dest);if(!destFile.open(QIODevice::WriteOnly)) {

#ifdef DEBUG

std::cerr<

#endifreturnfalse;

}

destFile.write(sourceFile.readAll());returnsourceFile.error()==QFile::NoError&&destFile.error()==QFile::NoError;

}/*** Instantiate a QFile

* Open the file

* Access the file through q QDataStream object.

*

* Must ensure that we read all the types in exactly the same order

* as we wrote them.

*

* If the DataStream is being purely used to read and write basic C++ data types,

* we dont' even need to call setVersion().

*

* If we want to read or write a file in one go. WE can avoid using QDataStream altogether

* and instead using QIODevice's write() and readAll() function.

* For example copy a file.*/intmain(intargc,char*argv[]) {//********Write data in to the file.********QImage image("Adium.png");

QMapmap;

map.insert("red", Qt::red);

map.insert("green", Qt::green);

C c(23);

QFile file("data.dat");if(!file.open(QIODevice::WriteOnly)) {

std::cerr<

}

QDataStream out(&file);

out.setVersion(QDataStream::Qt_4_3);

out<

file.close();//********Read data from the file.********quint32 value;

QMapmap2;

C c2;if(!file.open(QIODevice::ReadOnly)) {

std::cerr<

}

QDataStream in(&file);

in.setVersion(QDataStream::Qt_4_3);

in>>value>>map2>>c2;

file.close();

std::cout<

copy(QString("Adium.png"), QString("Copy_Adium.png"));return0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值