QBuffer类为QByteArray提供了一个QIODevice接口
#include <QtCore/QCoreApplication> #include <QBuffer> #include <QByteArray> #include <QDataStream> #include <QDebug> void write_buffer(int type, QBuffer& buffer) { if( buffer.open(QIODevice::WriteOnly) ) { QDataStream out(&buffer); out << type; if( type == 0 ) { out << QString("D.T.Software"); out << QString("3.1415"); } else if( type == 1 ) { out << 3; out << 1415; } else if( type == 2 ) { out << 3.1415; } buffer.close(); } } void read_buffer(QBuffer& buffer) { if( buffer.open(QIODevice::ReadOnly) ) { int type = -1; QDataStream in(&buffer); in >> type; if( type == 0 ) { QString dt = ""; QString pi = ""; in >> dt; in >> pi; qDebug() << dt; qDebug() << pi; } else if( type == 1 ) { int a = 0; int b = 0; in >> a; in >> b; qDebug() << a; qDebug() << b; } else if( type == 2 ) { double pi = 0; in >> pi; qDebug() << pi; } buffer.close(); } } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QByteArray array; QBuffer buffer(&array); write_buffer(2, buffer); read_buffer(buffer); return a.exec(); }
#include <QtCore/QCoreApplication> #include <QDir> #include <QFileInfo> #include <QFileInfoList> #include <QDebug> void test_dir() { const char* PATH = "C:/Users/hp/Desktop/QDir"; QDir dir; if( !dir.exists(PATH) ) { dir.mkdir(PATH); } if( dir.exists(PATH) ) { dir.cd(PATH); QStringList list = dir.entryList(); for(int i=0; i<list.count(); i++) { qDebug() << list[i]; } } } unsigned int calculate_size(QString path) { QFileInfo info(path); unsigned int ret = 0; if( info.isFile() ) { ret = info.size(); } else if( info.isDir() ) { QDir dir(path); QFileInfoList list = dir.entryInfoList(); for(int i=0; i<list.count(); i++) { if( (list[i].fileName() != ".") && (list[i].fileName() != "..") ) { ret += calculate_size(list[i].absoluteFilePath()); } } } return ret; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); test_dir(); qDebug() << calculate_size("C:/Users/hp/Desktop/QDir"); return a.exec(); } #include <QtCore/QCoreApplication> #include "Watcher.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Watcher watcher; watcher.addPath("C:/Users/hp/Desktop/text.txt"); watcher.addPath("C:/Users/hp/Desktop/QDir"); return a.exec(); } #include "Watcher.h" #include <QDebug> Watcher::Watcher(QObject *parent) : QObject(parent) { connect(&m_watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(statusChanged(const QString&))); connect(&m_watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(statusChanged(const QString&))); } void Watcher::statusChanged(const QString &path) { qDebug() << path << "is changed!"; } void Watcher::addPath(QString path) { m_watcher.addPath(path); } #ifndef _WATCHER_H_ #define _WATCHER_H_ #include <QObject> #include <QFileSystemWatcher> class Watcher : public QObject { Q_OBJECT QFileSystemWatcher m_watcher; private slots: void statusChanged(const QString& path); public: explicit Watcher(QObject *parent = 0); void addPath(QString path); }; #endif // WATCHER_H