1、判断文件是否存在
QFile file(path);
file.exists();
2、复制文件
bool copy(const QString &fileName, const QString &newName);
3、建立快捷方式
/* GetShorCutPath 该函数得到计算机特定位置的路径 nFolder 表示位置标示,可取
CSIDL_BITBUCKET 回收站
CSIDL_CONTROLS 控制面板
CSIDL_DESKTOP Windows桌面desktop;
CSIDL_DESKTOPDIRECTORY desktop的目录;
CSIDL_DRIVES 我的电脑
CSIDL_FONTS 字体目录
CSIDL_NETHOOD 网上邻居
CSIDL_NETWORK 网上邻居virtual folder
CSIDL_PERSONAL 我的文档
CSIDL_PRINTERS 打印机
CSIDL_PROGRAMS 程序组
CSIDL_RECENT 最近打开文档
CSIDL_SENDTO 发送到菜单项
CSIDL_STARTMENU 快启菜单
CSIDL_STARTUP 启动目录
CSIDL_TEMPLATES 临时文档
*/
shortcutName += ".lnk"; QString temppath = ""; GetShorCutPath(temppath,CSIDL_STARTMENU); temppath += "/"+shortcutName; QFile::link(appPath,temppath); void GetShorCutPath(QString &path,int nFolder) { LPITEMIDLIST pidl; LPMALLOC pShellMalloc; char szDir[400]=""; char szDir2[200]=""; if(SUCCEEDED(SHGetMalloc(&pShellMalloc))) { if(SUCCEEDED(SHGetSpecialFolderLocation(NULL,nFolder,&pidl))) { SHGetPathFromIDList(pidl,(LPWSTR)szDir); pShellMalloc->Free(pidl); } pShellMalloc->Release(); } //类型转换 char temp = szDir[0]; int start = 0; int start2 = 0; while(temp !='\0') { szDir2[start++] = temp; start2 += 2; temp = szDir[start2]; if (temp == '\\') { temp = '/'; } } szDir2[start] = '\0'; path = QString(szDir2); }
4、开机启动程序
void MainWindow::autoStart(IniFile &inifile,const QString &appPath) { QString flag; QString appName; appName = appPath.right(appPath.length()-appPath.lastIndexOf("/")-1); inifile.readIni("AUTOSTART",flag); if(flag == "true") { QSettings *reg = new QSettings("HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Run", QSettings::NativeFormat); reg->setValue(appName,appPath); } }
5、运行程序
QProcess *process = new QProcess; //这个不加析构,不退出
process->start(appPath);
6、删除目录及其下所有文件
void deleteDir(const QString &d) { QDir dir(d); foreach (QFileInfo inf, dir.entryInfoList(QDir::Dirs|QDir::Files)) { if(inf.isFile()) dir.remove(inf.absoluteFilePath()); else if(inf.isDir() && inf.fileName() != "." && inf.fileName() != "..") deleteDir(inf.absolutePath()+"/"+inf.fileName()); } dir.rmdir(dir.absolutePath()); }
7、抽取
/************************************************************************************* * * File: SEFileInfo.cpp * Version: 1.0 * * Author: James Spibey * Date: 04/08/1999 * E-mail: spib@bigfoot.com * * Implementation of the CSEFileInfo class * * You are free to use, distribute or modify this code * as long as this header is not removed or modified. * * *************************************************************************************/ #include "SEFileInfo.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif /******************************************************************************* * * Function: CSEFileInfo::CSEFileInfo * * Description: * Default Constructor * * Parameters: * None * * Return: * None *******************************************************************************/ CSEFileInfo::CSEFileInfo() { Reset(); } /******************************************************************************* * * Function: CSEFileInfo::~CSEFileInfo * * Description: * Destructor * * Parameters: * None * * Return: * None *******************************************************************************/ CSEFileInfo::~CSEFileInfo() { } /******************************************************************************* * * Function: CSEFileInfo::Reset * * Description: * Reset the class data members * * Parameters: * None * * Return: * None *******************************************************************************/ void CSEFileInfo::Reset() { m_nSize = 0; m_strPathname = ""; m_strFilename = ""; }
/************************************************************************************* * * File: SelfExtracter.cpp * Version: 1.0 * * Author: James Spibey * Date: 04/08/1999 * E-mail: spib@bigfoot.com * * Implementation of the CSelfExtracter class * * You are free to use, distribute or modify this code * as long as this header is not removed or modified. * * *************************************************************************************/ #include "Windows.h" #include "SelfExtractor.h" #include "QDebug" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #include "QFileDialog" #include "QMessageBox" #include "QDir" #include "IniFile.h" /******************************************************************************* * * Function: CSelfExtractor::CSelfExtractor * * Description: * Default Constructor * * Parameters: * None * * Return: * None *******************************************************************************/ CSelfExtractor::CSelfExtractor() { m_nFiles = 0; m_nTOCSize = 0; } /******************************************************************************* * * Function: CSelfExtractor::~CSelfExtractor * * Description: * Destructor * * Parameters: * None * * Return: * None *******************************************************************************/ CSelfExtractor::~CSelfExtractor() { } /******************************************************************************* * * Function: CSelfExtractor::ExtractAll * * Description: * Extract the current archive to the specified directory * * Parameters: * QString Dir: Destination Directory * funcPtr pFn: Pointer to a user defined callback function * void* UserData: User defined data to pass to the callback function * * Return: * int: Error Code * INPUT_FILE_ERROR - Failed to open the input file * OUTPUT_FILE_ERROR - Failed to create an output file *******************************************************************************/ int CSelfExtractor::ExtractAll(QString Dir, funcPtr pFn /*= NULL*/, void * userData /*= NULL*/) //如果用到这个,需要对getthisfilename做更改,如extract函数 { //Make sure the directory name has a trailing backslash EnsureTrailingBackSlash(Dir); QFile Thisfile(GetThisFileName()); //Archive (Usually itself) //qDebug()<<GetThisFileName(); //Read the Table of Contents int res = ReadTOC(GetThisFileName()); if(res != SUCCESS) return res; //Open the archive if(!Thisfile.open(QIODevice::ReadOnly)) return INPUT_FILE_ERROR; else { //Get the files out in reverse order so we can work out the offsets //Subtract 1 from the filecount as we are zero-based for(int i = (m_nFiles - 1); i >= 0 ; i--) { ExtractOne(&Thisfile, i, Dir); //Do the callback if(pFn != NULL) pFn(static_cast<void*>(&m_InfoArray[i]), userData); } //Close the archive Thisfile.close(); } return SUCCESS; } /******************************************************************************* * * Function: CSelfExtractor::Extract * * Description: * Extract a single file from the current archive to the specified directory * * Parameters: * int index: index in array of file * QString Dir: Destination Directory * * Return: * int: Error Code * INPUT_FILE_ERROR - Failed to open the input file * OUTPUT_FILE_ERROR - Failed to create an output file *******************************************************************************/ int CSelfExtractor::Extract(int index, QString Dir,QString &appName) { //Make sure the directory name has a trailing backslash EnsureTrailingBackSlash(Dir); QFile Thisfile(appName);//Archive (Usually itself) //GetThisFileName() //Read the Table of Contents int res = ReadTOC(appName); //GetThisFileName() if(res != SUCCESS) return res; //Open the archive if(!Thisfile.open(QIODevice::ReadOnly)) return INPUT_FILE_ERROR; else { ExtractOne(&Thisfile, index, Dir); //Close the archive Thisfile.close(); } return SUCCESS; } /******************************************************************************* * * Function: CSelfExtractor::ExtractOne * * Description: * Actual Data Extraction. Seeks to required offset in archive * and writes new file * * Parameters: * QFile* file: Pointer to the archive * int index: Index of file in array * QString Dir: Destination Dir * * Return: * int: Error Code *******************************************************************************/ int CSelfExtractor::ExtractOne(QFile* file, int index, QString Dir) { char buffer[1000]; //Buffer to read and write with QFile NewFile(Dir + m_InfoArray[index].GetFilename()); //Extracted File //Get the file size (in bytes) int FileSize = m_InfoArray[index].GetFileSize(); //Create the new file if(!NewFile.open(QIODevice::WriteOnly)) return OUTPUT_FILE_ERROR; //Seek to the correct Offset file->seek(m_InfoArray[index].GetFileOffset()); //Loop the data out from the archive DWORD dwWritten = 0; DWORD dwRead = 0; int AmountToRead = 0; while(TRUE) { //Read out 1000 bytes at a time or the remainder if //there is less than 1000 left. Exit if there is none left AmountToRead = FileSize - dwWritten; if(AmountToRead > 1000) AmountToRead = 1000; else if(AmountToRead == 0) break; dwRead = file->read(buffer, AmountToRead); NewFile.write(buffer, dwRead); dwWritten += dwRead; } //Close the output file NewFile.close(); return SUCCESS; } /******************************************************************************* * * Function: CSelfExtractor::ReadTOC * * Description: * Read the archive's Table of Contents * * Parameters: * QString Filename: Filename of the archive (full path) * * Return: * int: Error Code *******************************************************************************/ int CSelfExtractor::ReadTOC(QString Filename) { QFile Thisfile(Filename); //Archive file char buffer[1000]; //Buffer to read and write with //Clear the CSEFileInfo class array Reset(); //Open the archive if(!Thisfile.open(QIODevice::ReadOnly)) return NO_SOURCE; else { //Read in the signature int filelen = Thisfile.size(); Thisfile.seek(filelen- static_cast<int>(strlen(SIGNATURE))); Thisfile.read(buffer, strlen(SIGNATURE)); //Check that it matches if(strncmp(buffer, SIGNATURE, strlen(SIGNATURE)) != 0) return INVALID_SIG; else { //Read Number of files int LastOffset = strlen(SIGNATURE) + static_cast<int>(sizeof(int)); Thisfile.seek(filelen-LastOffset); Thisfile.read((char*)&m_nFiles, sizeof(int)); //If there are no files in the archive, there is nothing to extract if(m_nFiles == 0) return NOTHING_TO_DO; //Read the TOC in. The array is filled in reverse to ensure that it //corresponds to the data segment for(int i = (m_nFiles - 1); i >= 0 ; i--) { int nSize = 0; int nOffset = 0; int len = 0; LastOffset += sizeof(int); //Get Length of Pathname Thisfile.seek(filelen-LastOffset); Thisfile.read((char*)&len, sizeof(int)); LastOffset += len; //Get Path Name Thisfile.seek(filelen-LastOffset); Thisfile.read(buffer, len); LastOffset += sizeof(int); //Get File Size Thisfile.seek(filelen-LastOffset); Thisfile.read((char*)&nSize, sizeof(int)); LastOffset += sizeof(int); //Get File Offset Thisfile.seek(filelen-LastOffset); Thisfile.read((char*)&nOffset, sizeof(int)); //Set the data in the array m_InfoArray[i].SetSize(nSize); QString Temp(buffer); m_InfoArray[i].SetFilename(Temp.left(len)); m_InfoArray[i].SetOffset(nOffset); } //Record the total size of the TOC for use //when extracting the data segment m_nTOCSize = LastOffset; } } //Close the archive Thisfile.close(); return SUCCESS; } /******************************************************************************* * * Function: CSelfExtractor::Reset * * Description: * Reset the CSEFileInfo Array * * Parameters: * None * * Return: * None *******************************************************************************/ void CSelfExtractor::Reset() { for(int i = 0; i < MAX_FILES; i++) m_InfoArray[i].Reset(); m_nFiles = 0; m_nTOCSize = 0; } /******************************************************************************* * * Function: CSelfExtractor::EnsureTrailingBackSlash * * Description: * Ensure that the string has a trailing backslash * * Parameters: * QString &string: Pathname * * Return: * QString: Pathname *******************************************************************************/ QString CSelfExtractor::EnsureTrailingBackSlash(QString &string) { int len = string.length(); QDir DIR; if(!DIR.exists(string)) { DIR.mkdir(string); } if(string[len - 1] != '\\') { string += "/"; } return string; } /******************************************************************************* * * Function: CSelfExtractor::GetThisFileName * * Description: * Get this executable's file path * * Parameters: * None * * Return: * QString: Full Path for this executable *******************************************************************************/ QString CSelfExtractor::GetThisFileName() { QString path; QDir dir; QString appName; IniFile iniFile("C:/DymindTemp/TempPath/qt.ini"); iniFile.readIni("AppTitle",appName); path=dir.currentPath(); path +="/"; path += appName+".exe"; //改成install //path += "INSTALL.exe" ; QString showtext; showtext = "apppath =" ; showtext += path; return path; }
#include "zipimplement.h" #include <direct.h> #include <vector> #include <xstring> #include "QFileInfo" #include <QDir> #include <QByteArray> #include "QFileInfoList" #include <QFile> #include "QDebug" #include "QMessageBox" CZipImplement::CZipImplement(void) { m_progress.total = 0; m_progress.current = 0; } CZipImplement::~CZipImplement(void) { } //解压文件到目录--------------------------------------------------------------------- BOOL CZipImplement::Zip_UnPackFiles(QString &mZipFileFullPath, QString& mUnPackPath,funcPtr function,void *userData) { //首先判断参数是否为空,为空则返回 false------------------------------- if ((mUnPackPath == "") || (mZipFileFullPath == "")) { return FALSE ; } //判断文件时否是文件类型,如果不是返回 false----------------------------- QFileInfo fileinfo(mZipFileFullPath); if(!fileinfo.isFile()) { return FALSE; } //如果解压缩的路径不存在 试图创建它,只能有一级目录没有创建------------- QString tZipFilePath = mUnPackPath; FolderExist(tZipFilePath); tZipFilePath += "/"; //打开ZIP文件---------------------------------------------------------- char *filechar; QByteArray ba = mZipFileFullPath.toLocal8Bit(); //Qstring 转换成char * filechar = ba.data(); zFile=unzOpen(filechar); if(zFile == 0) { return FALSE; } unz_global_info gi; unz_file_info FileInfo; if (unzGetGlobalInfo(zFile, &gi ) == UNZ_OK ) { m_progress.total = gi.number_entry; for ( unsigned int i = 0; i < gi.number_entry; ++i ) { m_progress.current = i; char file[256] = { 0 }; char ext[256] = { 0 }; char com[1024] = { 0 }; if ( unzGetCurrentFileInfo( zFile, &FileInfo, file, sizeof(file), ext, 256, com, 1024 ) != UNZ_OK ) { return FALSE; } if( !( FileInfo.external_fa & FILE_ATTRIBUTE_DIRECTORY ) ) //文件,否则为目录 { unzOpenCurrentFile(zFile); } char data[1024] = { 0 }; int size; QString path = tZipFilePath + file; FolderExist(path); QFile File(path); File.open( QIODevice::WriteOnly); while(true) { size= unzReadCurrentFile(zFile,data,sizeof(data)); if(size <= 0) { break; } File.write(data, size); } File.close(); unzCloseCurrentFile(zFile); if( i < gi.number_entry - 1 && unzGoToNextFile( zFile ) != UNZ_OK ) { return FALSE; } } unzClose(zFile); if(function !=NULL) { function(static_cast<void*>(&m_progress),userData); } } else { return FALSE; } return TRUE; } void CZipImplement::FolderExist(QString& strPath) { //判定最后一级目录是否存在,如果不存在则创建目录 QDir *dir = new QDir; int index = 0; //首先判断是否为文件路径 if(strPath.contains(".")) { index = strPath.lastIndexOf("/"); } else { index = strPath.length(); } QString str = strPath.left(index); if(!dir->exists(str)) { dir->mkdir(str); } delete dir; dir = NULL; }
#pragma once #include "zip.h" #include "unzip.h" #include <QString> struct ProGress { int total; int current; }; typedef void (*funcPtr)(void *,void*); class CZipImplement { public: CZipImplement(void); ~CZipImplement(void); private: unzFile zFile; //Zip文件句柄 public: //*************************************************** //函数功能:解压zip文件到目录下 //参数定义:mZipFileFullPath ---zip文件绝对路径,mUnPackPath--- 输出文件目录 // //*************************************************** BOOL Zip_UnPackFiles(QString &mZipFileFullPath, QString& mUnPackPath,funcPtr function = NULL,void *userData = NULL); //*************************************************** //函数功能:判断目录是否存在,如不存在创建目录 //参数定义:strPath-----目录路径 // //*************************************************** void FolderExist(QString& strPath); public: ProGress m_progress; };
/************************************************************************************* * * File: SelfExtracter.h * Version: 1.0 * * Author: James Spibey * E-mail: spib@bigfoot.com * * Specification of the CSelfExtracter class * * This code was based on suggestions from :- * Levente Farkas, Roger Allen, G黱ter (surname unknown) * * You are free to use, distribute or modify this code * as long as this header is not removed or modified. * * Self Extractor (SFX) File Format * --------------------------------- * * Starting from the end of the archive and working backwards :- * * Header Info * 10 bytes Signature - Identifier for SFX archive * 4 bytes Number of files in archive * * Table of Contents * * Contains one record in the following format for each file * 4 bytes Length of filename * variable Filename * 4 bytes Length of File * 4 bytes Offset in archive to data * * Data Segment * Each file is written (uncompressed) here in the order of the TOC * * After this is the extractor executable. * *************************************************************************************/ #if !defined(AFX_SELFEXTRACTOR_H__849C04B2_4988_11D3_A8BC_0050043A01C0__INCLUDED_) #define AFX_SELFEXTRACTOR_H__849C04B2_4988_11D3_A8BC_0050043A01C0__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "QFile" #include "SEFileInfo.h" #include "QDir" #include "QString" #define NO_SOURCE 1000 #define INVALID_SIG 1001 #define SUCCESS 1002 #define COPY_FAILED 1003 #define NOTHING_TO_DO 1004 #define OUTPUT_FILE_ERROR 1005 #define INPUT_FILE_ERROR 1006 #define RESOURCE_ERROR 1007 #define MAX_FILES 256 #define SIGNATURE "!LYME_SFX!" typedef void (* funcPtr)(void *, void*); class CSelfExtractor { public: CSelfExtractor(); virtual ~CSelfExtractor(); //Creation //Extraction int Extract(int index, QString Dir,QString &appName); int ExtractAll(QString dir, funcPtr function = NULL, void * userData = NULL);// int ReadTOC(QString Filename); //Data retrieval inline int GetFileSize(int index){return m_InfoArray[index].GetFileSize();} inline int GetFileCount(){return m_nFiles;} CSEFileInfo GetItem(int item){return m_InfoArray[item];} //Helpers void Reset(); protected: //Helpers QString GetThisFileName();// QString EnsureTrailingBackSlash(QString &string); int CreateArchive(QFile* fp, funcPtr function, void* userData); int ExtractOne(QFile* fp, int index, QString Dir); //Data QString m_strWorkingDir; CSEFileInfo m_InfoArray[MAX_FILES]; //Array of file information int m_nFiles; //No of files in archive int m_nTOCSize; //Size of Table of contents }; #endif // !defined(AFX_SELFEXTRACTOR_H__849C04B2_4988_11D3_A8BC_0050043A01C0__INCLUDED_)
/************************************************************************************* * * File: SEFileInfo.h * Version: 1.0 * * Author: James Spibey * Date: 04/08/1999 * E-mail: spib@bigfoot.com * * Specification of the CSEFileInfo class * * You are free to use, distribute or modify this code * as long as this header is not removed or modified. * * This class holds data regarding each file in an archive * *************************************************************************************/ #if !defined(AFX_SEFILEINFO_H__5C3D775E_497B_11D3_A8BC_0050043A01C0__INCLUDED_) #define AFX_SEFILEINFO_H__5C3D775E_497B_11D3_A8BC_0050043A01C0__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "QString" #include "QFile" class CSEFileInfo { public: CSEFileInfo(); ~CSEFileInfo(); void SetFilename(QString file){m_strFilename = file;} void SetSize(int size){m_nSize = size;} void SetOffset(int offset){m_nOffset = offset;} QString GetPathname(){return m_strPathname;} QString GetFilename(){return m_strFilename;} int GetFileSize(){return m_nSize;} int GetFileOffset(){return m_nOffset;} void Reset(); protected: QString m_strFilename; //Name of file QString m_strPathname; //Path to file to add int m_nSize; //Size of file int m_nOffset; //Start Offset }; #endif // !defined(AFX_SEFILEINFO_H__5C3D775E_497B_11D3_A8BC_0050043A01C0__INCLUDED_)
CZipImplement zipimp;
BOOL flag = zipimp.Zip_UnPackFiles(SourcePath,installPath,AddCallBack,(void*)this);
void QMyWidgetSeven::AddCallBack(void * CallbackdData,void * userData) { ProGress *pData = static_cast<ProGress *>(CallbackdData); QMyWidgetSeven *pdlg = static_cast<QMyWidgetSeven*>(userData); int num = (pData->current+1)*1000/(pData->total); pdlg->progressBar->setValue(num); }