Chinaunix首页 | 论坛 | 博客
  • 博客访问: 215983
  • 博文数量: 145
  • 博客积分: 3000
  • 博客等级: 中校
  • 技术积分: 1720
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-14 18:42
文章分类

全部博文(145)

文章存档

2011年(1)

2009年(144)

我的朋友

分类: LINUX

2009-07-22 18:56:33

by tangke <> 2009-06-08

#include
#include
#include
#include
#include
class C {
public:
   C(quint32 value = 0) :
       value(value) {
   }
   // Override operator << and >>
   friend QDataStream &operator<<(QDataStream &out, const C &obj);
   friend QDataStream &operator>>(QDataStream &in, C &obj);
   quint32 getValue() const {
       return value;
   }
private:
   quint32 value;
};
QDataStream &operator<<(QDataStream &out, const C &obj) {
   out << obj.value;
   return out;
}
QDataStream &operator>>(QDataStream &in, C &obj) {
   in >> obj.value;
   return in;
}
/**
* Copy a file
*/
bool copy(const QString &source, const QString &dest) {
   QFile sourceFile(source);
   if (!sourceFile.open(QIODevice::ReadOnly)) {
#ifdef DEBUG
       std::cerr << sourceFile.errorString().toStdString() << std::endl;
#endif
       return false;
   }
   QFile destFile(dest);
   if (!destFile.open(QIODevice::WriteOnly)) {
#ifdef DEBUG
       std::cerr << destFile.errorString().toStdString() << std::endl;
#endif
       return false;
   }
   destFile.write(sourceFile.readAll());
   return sourceFile.error() == QFile::NoError && destFile.error()
           == QFile::NoError;
}
/**
* Instantiate a QFile
* Open the file
* Access the file through 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.
*/
int main(int argc, char *argv[]) {
   //********Write data in to the file.********
   QMap map;
   map.insert("red", Qt::red);
   map.insert("green", Qt::green);
   C c(23);
   QFile file("data.dat");
   if (!file.open(QIODevice::WriteOnly)) {
       std::cerr << "Cannot open the file: Write." << file.errorString().toStdString() << std::endl;
       return 1;
   }
   QDataStream out(&file);
   out.setVersion(QDataStream::Qt_4_3);
   out << quint32(7456) << map << c;
   file.close();
   //********Read data from the file.********
   quint32 value;
   QMap map2;
   C c2;
   if (!file.open(QIODevice::ReadOnly)) {
       std::cerr << "Cannot open the file: Read." << file.errorString().toStdString() << std::endl;
       return 2;
   }
   QDataStream in(&file);
   in.setVersion(QDataStream::Qt_4_3);
   in >> value >> map2 >> c2;
   file.close();
   std::cout << value << std::endl << c2.getValue();
   copy(QString("Adium.png"), QString("Copy_Adium.png"));
   return 0;
}
阅读(1541) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~