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

被折叠的 条评论
为什么被折叠?



