• 4143阅读
  • 1回复

[原创]迷你封装第一蛋: 哈希文件类 QHashFile [复制链接]

上一主题 下一主题
 

只看楼主 倒序阅读 楼主  发表于: 2011-10-14
QHashFile
  1. #include "qhashfile.h"


qhashfile.h
  1. #ifndef QHASHFILE_H
  2. #define QHASHFILE_H
  3. #include <QtCore/QFile>
  4. #include <QtCore/QByteArray>
  5. #include <QtCore/QCryptographicHash>
  6. class QHashFile
  7. {
  8.     public:
  9.     static QByteArray hash(QFile *file, QCryptographicHash::Algorithm method = QCryptographicHash::Md5);
  10.     static QByteArray hash(const QString &fileName, QCryptographicHash::Algorithm method = QCryptographicHash::Md5);
  11. };
  12. #endif//QHASHFILE_H

qhashfile.cpp
  1. /*
  2.   Publish by Eric Chow at 2011/10/14.
  3.   E-Mail: echow.always@live.com.
  4. */
  5. /*!
  6.   \class QHashFile
  7.   \brief The QHashFile class is tool class for fast hash file.
  8. */
  9. #include "qhashfile.h"
  10. /*!
  11.   \fn QByteArray QHashFile::hash(QFile *file, QCryptographicHash::Algorithm method)
  12.   \brief Hash file with the file object \a file and the specific method \a method, and return the result.
  13. */
  14. QByteArray QHashFile::hash(QFile *file, QCryptographicHash::Algorithm method)
  15. {
  16.     Q_CHECK_PTR(file);
  17.     if ((!file) || (!file->isReadable())) {
  18.         return QByteArray();
  19.     }
  20.     if (file->pos() != 0) {
  21.         if (!file->seek(0)) {
  22.             return QByteArray();
  23.         }
  24.     }
  25.     QCryptographicHash hash(method);
  26.     char buffer[2048] = {0};
  27.     qint64 numberOfReadBytes = 0;
  28.     qint64 remainingBytes = file->size();
  29.     while (remainingBytes) {
  30.         numberOfReadBytes = remainingBytes > 2048 ? 2048 : remainingBytes;
  31.         if (numberOfReadBytes == file->read(buffer, numberOfReadBytes))
  32.             hash.addData(buffer, numberOfReadBytes);
  33.         else
  34.             return QByteArray();
  35.         remainingBytes -= numberOfReadBytes;
  36.     }
  37.     return hash.result();
  38. }
  39. /*!
  40.   \fn QByteArray QHashFile::hash(const QString &fileName, QCryptographicHash::Algorithm method)
  41.   \brief Hash file with the file name \a fileName and the specific method \a method, and return the result.
  42. */
  43. QByteArray QHashFile::hash(const QString &fileName, QCryptographicHash::Algorithm method)
  44. {
  45.     QByteArray result;
  46.     QFile file(fileName);
  47.     if (file.open(QFile::ReadOnly)) {
  48.         result = hash(&file, method);
  49.         file.close();
  50.     }
  51.     return result;
  52. }




附件: hashfile.rar (2 K) 下载次数:5
离线ppdayz

只看该作者 1楼 发表于: 2011-10-15
挺不错的,最后要输出的化要toHex();
快速回复
限100 字节
 
上一个 下一个