c++ 文件及文件夹操作(三)
一、 获得文件夹下的所有文件路径
void GetAllPath(const string& sSrcPath, vector<string>& vtPath) { struct _finddata_t fileinfo; long lHandle = -1; int iFind = 0; string sFile = sSrcPath + "\*.*"; lHandle = _findfirst(sFile.c_str(), &fileinfo); if (lHandle != -1) { iFind = _findnext(lHandle, &fileinfo); while (!iFind) { if (fileinfo.name[0]!="."&& (fileinfo.attrib&_A_SUBDIR)) { string sTemp; sTemp = sSrcPath + "\" + fileinfo.name; GetAllPath(sTemp, vtPath); } iFind = _findnext(lHandle, &fileinfo); } vtPath.push_back(sSrcPath); } _findclose(lHandle); }
BOOL DeleteFileExByFileExt(const char * pszPath, const char * pszExt) { char szFind[MAX_PATH]; WIN32_FIND_DATA FindFileData; strcpy(szFind,pszPath); strcat(szFind,"\*.*"); HANDLE hFind=::FindFirstFile(szFind,&FindFileData); if(INVALID_HANDLE_VALUE == hFind) return false; int nkey=0; while(TRUE) { if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(FindFileData.cFileName[0]!=".") { strcpy(szFind,pszPath); strcat(szFind,"\"); strcat(szFind,FindFileData.cFileName); DeleteFileByFileExt(szFind,pszExt); } } else { string strFile = FindFileData.cFileName; if (strFile.find(pszExt) != -1) { strcpy(szFind,pszPath); strcat(szFind,"\"); strcat(szFind,FindFileData.cFileName); DeleteFile(szFind); } } if(!FindNextFile(hFind,&FindFileData)) break; } FindClose(hFind); return true; }
三、 删除文件夹下所有文件
BOOL RemoveAllFile(CString strPath) { CFileFind ff; BOOL bFind = ff.FindFile(strPath+"\*.*"); while(bFind) { bFind = ff.FindNextFile(); if(ff.IsDots()) continue; if(ff.IsDirectory()) { RemoveAllFile(ff.GetFilePath()); RemoveDirectory(ff.GetFilePath()); } else { CFile::Remove(ff.GetFilePath()); } } RemoveDirectory(strPath); return TRUE; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: C++ 文件及文件夹操作(二)
- 下一篇: C++文件操作——创建和删除文件夹