天天看點

Qt檔案QFile 和檔案夾QDir一、QFileInfo的簡單用法二、 建立檔案夾三、判斷是否存在子目錄四、疊代删除檔案夾五、擷取一個目錄下所有檔案夾的名字六、拷貝檔案七、疊代拷貝檔案夾

一、QFileInfo的簡單用法

參考連結:http://blog.sina.com.cn/s/blog_3e62c50d01013xd4.html

QFileInfo的幾個構造函數:

QFileInfo ( )

QFileInfo ( const QString & file )

QFileInfo ( const QFile & file )

QFileInfo ( const QDir & dir, const QString & file )

QFileInfo ( const QFileInfo & fileinfo )

一般用法:

QFileInfo fileInfo(path);

//or

QFileInfo fileInfo;

fileInfo.setFile(path);
           

bool            exists(); 判斷檔案是否存在,若存在傳回true。

qint64         size(); 擷取檔案大小,傳回bytes。

//路徑和檔案名相關:

QString        path(); 傳回檔案路徑,不包含檔案名。

QString        filePath(); 傳回檔案路徑,包含檔案名。

QString         fileName(); 傳回檔案名稱。

// 例子如下

//檔案名
 QString file_name = fileinfo.fileName();
 qDebug()<<file_name<<endl;

 //檔案字尾
 QString file_suffix = fileinfo.suffix();
 qDebug()<<file_suffix<<endl;

//絕對路徑
 QString file_path = fileinfo.absolutePath();
qDebug()<<file_path<<endl;
           
QFileInfo fileInfo("/home/dipper/xyz.tar.gz");

fileInfo.path(); // returns "/home/dipper"

fileInfo.fileName(); // returns "xyz.tar.gz"

fileInfo.baseName(); // returns "xyz"

fileInfo.completeBaseName(); // returns "xyz.tar"

fileInfo.suffix(); // returns "gz"

fileInfo.completeSuffix(); // returns "tar.gz"

           

//類型:

bool                  isFile(); 判斷是否是檔案。

bool                  isDir(); 判斷是否是路徑。

bool                  isSymLink(); 判斷是否是符号連結。

//

QString        symLinkTarget(): 傳回符号連結的檔案

//日期相關:

QDateTime   created(); 建立時間

QDateTime   lastModified(); 最近修改時間

QDateTime   lastRead(); 最近讀時間

//權限:

isReadable(), isWritable(), isExecutable()

//所有者:

ower(), owerId(), group(), groupId(), permissions(),

permission(QFile::Permissions permissions)

dir(): 傳回父目錄

//下面三個都傳回"~/examples/191697"

QFileInfo fileInfo1("~/examples/191697/.");

QFileInfo fileInfo2("~/examples/191697/..");

QFileInfo fileInfo3("~/examples/191697/main.cpp");

//下面三個都傳回"."

QFileInfo fileInfo4(".");

QFileInfo fileInfo5("..");

QFileInfo fileInfo6("main.cpp");

//相對路徑和絕對路徑

QString absolute = "/local/bin";

QString relative = "local/bin";

QFileInfo absFile(absolute);

QFileInfo relFile(relative);

二、 建立檔案夾

//folder 是路徑,可以是絕對或相對路徑
bool PathHelper::createDirectory(QString folder)
{
 
	// 檢查目錄是否存在,若不存在則建立
	QDir dir;
	if (!dir.exists(folder))
	{
		bool res = dir.mkpath(folder);
		return true;
	}
	else 
	{
		return false;
	}
}
           

三、判斷是否存在子目錄

bool judgeDir(QDir dir)
 {
     dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
     foreach(QFileInfo fileInfo, dir.entryInfoList())
     {
         if(fileInfo.isDir())
         {
             return true;
         }
         else if(fileInfo.isFile())
         {
             return true;
         }
         else
         {
             return false;
         }
    }
     return true;
 }
           

四、疊代删除檔案夾

       疊代

//删除檔案夾
bool DelDir(const QString &path)
{
	if (path.isEmpty()) {
		return false;
	}
	QDir dir(path);
	if (!dir.exists()) {
		return true;
	}
	dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); //設定過濾
	QFileInfoList fileList = dir.entryInfoList(); // 擷取所有的檔案資訊
	foreach(QFileInfo file, fileList) { //周遊檔案資訊
		if (file.isFile()) { // 是檔案,删除
			file.dir().remove(file.fileName());
		}
		else { // 遞歸删除
			PlanImageForm::DelDir(file.absoluteFilePath());
		}
	}
	return dir.rmpath(dir.absolutePath()); // 删除檔案夾
}
           

     不疊代

bool PathHelper::DelDir(const QString  name)
{
	PathHelper::intial();
	QString path = productPath + "/" + name;
	if (path.isEmpty()) {
		return false;
	}
	QDir dir(path);
	if (!dir.exists()) {
		return true;
	}
	bool flag =RemoveDirectory(path.toStdWString().c_str());
	//dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); //設定過濾
	//QFileInfoList fileList = dir.entryInfoList(); // 擷取所有的檔案資訊
	//foreach(QFileInfo file, fileList) { //周遊檔案資訊
	//	if (file.isFile()) { // 是檔案,删除
	//		file.dir().remove(file.fileName());
	//	}
	//	else { // 遞歸删除
	//		DelDir(file.absoluteFilePath());
	//	}
	//}
	return flag; // 删除檔案夾
}
           

五、擷取一個目錄下所有檔案夾的名字

1、不疊代,擷取目錄下的檔案名

QStringList getFileNames(const QString &path)
{
    QDir dir(path);
    QStringList nameFilters;
    //nameFilters << "*.jpg" << "*.png";
    QStringList files = dir.entryList(nameFilters, QDir::NoSymLinks|QDir::Dirs|QDir::Files|QDir::Readable|QDir::NoDotAndDotDot , QDir::Name);
    return files;
}
           

2、疊代,擷取目錄下(包含子目錄)下的所有檔案名,使用時需要修改。

/************壓縮檔案************/
int writer(QString ZipSrc)
{

    QFileInfo fileinfo(ZipSrc);
    if(fileinfo.isFile())
    {
        //檔案名
        QString file_name = fileinfo.fileName();
        qDebug()<<file_name<<endl;

        //檔案字尾
        QString file_suffix = fileinfo.suffix();
        qDebug()<<file_suffix<<endl;

        //絕對路徑
        QString file_path = fileinfo.absolutePath();
        qDebug()<<file_path<<endl; 

    }
    else if(fileinfo.isDir())
    {
        //檔案夾名
        QString file_name = fileinfo.fileName();
        qDebug()<<file_name<<endl;

        //檔案夾絕對路徑
        QString file_path = fileinfo.absolutePath();
        qDebug()<<file_path<<endl;

        QStringList files = getFileNames(ZipSrc);
        foreach (QString var, files)
        {
            qDebug()<<var<<endl;
            QString subZipSrc=ZipSrc+"/"+var;
            writer(subZipSrc) ;
        }
    }
    return 0;
}
           

3、疊代/不疊代  擷取所有的目錄或者子目錄

void PathHelper::GetAllFileFolder(std::vector<QString>& folder)
{
	PathHelper::intial();
 
	QDir dir(productPath);
	dir.setFilter(QDir::Dirs);
//周遊
	foreach(QFileInfo fullDir, dir.entryInfoList())
	{
		if (fullDir.fileName() == "." || fullDir.fileName() == "..") continue;
		folder.push_back(fullDir.baseName());
 
		// this->GetAllFileFolder(fullDir.absoluteFilePath(), folder);
	}
 
 
}
 
           

六、拷貝檔案

//拷貝檔案:
bool MyTest007::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
	toDir.replace("\\","/");
	if (sourceDir == toDir){
		return true;
	}
	if (!QFile::exists(sourceDir)){
		return false;
	}
	QDir *createfile     = new QDir;
	bool exist = createfile->exists(toDir);
	if (exist){
		if(coverFileIfExist){
			createfile->remove(toDir);
		}
	}//end if
 
	if(!QFile::copy(sourceDir, toDir))
	{
		return false;
	}
	return true;
}

           

七、疊代拷貝檔案夾

bool copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
{
	QDir sourceDir(fromDir);
	QDir targetDir(toDir);
	if (!targetDir.exists()) {    /**< 如果目标目錄不存在,則進行建立 */
		if (!targetDir.mkdir(targetDir.absolutePath()))
			return false;
	}

	QFileInfoList fileInfoList = sourceDir.entryInfoList();
	foreach(QFileInfo fileInfo, fileInfoList) {
		if (fileInfo.fileName() == "." || fileInfo.fileName() == "..")
			continue;

		if (fileInfo.isDir()) {    /**< 當為目錄時,遞歸的進行copy */
			if (!PlanImageForm::copyDirectoryFiles(fileInfo.filePath(),
				targetDir.filePath(fileInfo.fileName()),
				coverFileIfExist))
				return false;
		}
		else {            /**< 當允許覆寫操作時,将舊檔案進行删除操作 */
			if (coverFileIfExist && targetDir.exists(fileInfo.fileName())) {
				targetDir.remove(fileInfo.fileName());
			}

			/// 進行檔案copy
			if (!QFile::copy(fileInfo.filePath(),
				targetDir.filePath(fileInfo.fileName()))) {
				return false;
			}
		}
	}
	return true;
}
           

繼續閱讀