1.在項目中建立新文件app
NCFileSave.cppblog
NCFileSave.hget
2.NCFileSave.h的內容it
#ifndef NCFILESAVE_H #define NCFILESAVE_H #include <QFile> #include <QDateTime> #include <QApplication> #include<QTextStream> class NCFileSave { public: NCFileSave(); ~NCFileSave(); public: //存儲的文件名稱 QString getFileName(); void openfile(); //操做符的定義 QTextStream& operator <<(const QString& val); private: QFile _outFile; QTextStream _textStream; }; #endif // NCFILESAVE_H
3.NCFileSave.cpp的內容io
#include "NCFileSave.h" NCFileSave::NCFileSave() { } NCFileSave::~NCFileSave() { if(_outFile.isOpen())_outFile.close(); } QString NCFileSave::getFileName() { QDateTime time = QDateTime::currentDateTime(); return QString("WXH_%1").arg(time.toString("YYYYMMddThhmmss")); } void NCFileSave::openfile() { if(_outFile.isOpen())_outFile.close(); //文件的名稱 QString root = QApplication::applicationDirPath(); root += QString("/"+getFileName()); if(_outFile.open(QIODevice::WriteOnly|QIODevice::Text)) { _textStream.setDevice(&_outFile); } } QTextStream &NCFileSave::operator <<(const QString &val) { _textStream << val; _textStream.flush(); return _textStream; }
4.在主文件中調用class
#include< NCFileSave.h> NCFileSave _fileSave; _fileSave.openfile(); _fileSave << "mmmmmmmmmmm" << "\n";
5.在保存的路徑下可看到保存的文件file