bool OperCFThread::DeleteList( FS* fs, FSPath& _path, FSList& list ) { if ( Info()->Stopped() ) { return false; } FSPath path = _path; int cnt = path.Count(); for ( FSNode* node = list.First(); node; node = node->next ) { if ( node->extType ) { continue; } path.SetItemStr( cnt, node->Name() ); if ( node->IsDir() && !node->st.IsLnk() ) { if ( !DeleteDir( fs, path ) ) { return false; } if ( !RmDir( fs, path ) ) { return false; } continue; } if ( !DeleteFile( fs, path ) ) { return false; } } return true; }
BOOL CMyUtils::DeleteDir(LPCTSTR lpDirPath) { CFileFind finder; BOOL bFind; TCHAR strFindPath[MAX_PATH]; _stprintf(strFindPath, _T("%s\\*"), lpDirPath); bFind = finder.FindFile(strFindPath); while (bFind) { bFind = finder.FindNextFile(); if (!finder.IsDirectory()) { if (!DeleteFile(finder.GetFilePath())) { finder.Close(); return FALSE; } } else if (!finder.IsDots()) { if (!DeleteDir(finder.GetFilePath())) { finder.Close(); return FALSE; } } } finder.Close(); return RemoveDirectory(lpDirPath); }
BOOL CHistoryManagerXP::CleanUpdate() { CStringW dir = m_strWinTemp + L"BankUpdate"; return DeleteDir(dir); return TRUE; }
eOpcodeResult WINAPI Script_FS_DeleteDirectory(CScript* script) /**************************************************************** Opcode Format 0B01=2,delete_directory %1d% with_all_files_and_subdirectories %2d% //IF and SET ****************************************************************/ { script->Collect(2); int DeleteAllInsideFlag; BOOL result; DeleteAllInsideFlag = Params[1].nVar; if (DeleteAllInsideFlag) { //remove directory with all files and subdirectories result = DeleteDir(Params[0].cVar); } else { //try to remove as empty directory result = RemoveDirectory(Params[0].cVar); } script->UpdateCompareFlag(result); return OR_CONTINUE; }
BOOL DeleteDir(const std::wstring& sDir) { std::wstring sDirectory=sDir; if(sDirectory.at(sDirectory.length()-1)!=L'\\') { sDirectory=sDirectory.append(L"\\"); } sDirectory=sDirectory.append(L"*.*"); WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; hFind = FindFirstFile(sDirectory.c_str(), &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { return TRUE; } while (FindNextFile(hFind, &FindFileData) != 0) { bool bIsDirectory=((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!=0); if(bIsDirectory && (wcscmp(FindFileData.cFileName,L".")==0 || wcscmp(FindFileData.cFileName,L"..")==0)) { continue; } std::wstring sFileName=sDir; if(sFileName.at(sFileName.length()-1)!=L'\\') { sFileName=sFileName.append(L"\\"); } sFileName.append(FindFileData.cFileName); if(bIsDirectory) { if(!DeleteDir(sFileName.c_str())) { return FALSE; } if (!RemoveDirectory(sFileName.c_str())) { return FALSE; } } else { if(!DeleteFile(sFileName.c_str())) { return FALSE; } } } FindClose(hFind); return TRUE; }
// Deletes the given directory and anything under it. Returns true on success. bool DeleteDirRecursively(const std::string &directory) { LOG_INFO(TCOMMON, "DeleteDirRecursively: %s", directory.c_str()); #ifdef _WIN32 // Find the first file in the directory. WIN32_FIND_DATA ffd; HANDLE hFind = FindFirstFile((directory + "\\*").c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { FindClose(hFind); return false; } // windows loop do { const std::string virtualName = ffd.cFileName; #else struct dirent dirent, *result = NULL; DIR *dirp = opendir(directory.c_str()); if (!dirp) { return false; } // non windows loop while (!readdir_r(dirp, &dirent, &result) && result) { const std::string virtualName = result->d_name; #endif // check for "." and ".." if (((virtualName[0] == '.') && (virtualName[1] == '\0')) || ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0'))) { continue; } std::string newPath = directory + '/' + virtualName; if (IsDirectory(newPath)) { if (!DeleteDirRecursively(newPath)) return false; } else { if (!DeleteFile(newPath)) return false; } #ifdef _WIN32 } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else } closedir(dirp); #endif DeleteDir(directory); return true; }
static BOOL DeleteDir(char * path) { WIN32_FIND_DATA finddata; HANDLE hfind = NULL; char * pdir; int nDirLength = strlen( path ) + 16; pdir=new char[nDirLength]; ZeroMemory( pdir, nDirLength ); StringCbCopy( pdir, nDirLength, path ); if(path[strlen(path)-1]!='\\') StringCbCat( pdir, nDirLength, "\\*.*" ); else StringCbCat( pdir, nDirLength, "*.*" ); hfind=FindFirstFile(pdir,&finddata); if(hfind==INVALID_HANDLE_VALUE) return FALSE; delete []pdir; do { int nPathLength = strlen(path)+strlen(finddata.cFileName)+16; pdir=new char[nPathLength]; ZeroMemory( pdir, nPathLength ); _stprintf_s( pdir, nPathLength, "%s\\%s", path, finddata.cFileName ); if(strcmp(finddata.cFileName,".")==0 ||strcmp(finddata.cFileName,"..")==0) { delete []pdir; pdir = NULL; RemoveDirectory(pdir); continue; } if((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==0) DeleteFile(pdir); else DeleteDir(pdir); delete []pdir; pdir = NULL; }while(FindNextFile(hfind,&finddata)); FindClose( hfind ); hfind = NULL; if(RemoveDirectory(path)) return TRUE; else return FALSE; }
bool TryDeleteDir(const char* dir, bool recursively) { if (recursively) { std::string t = RealPath(dir); TValueArray<std::string> files; GetFilesAndDirs(t.c_str(), false, &files); for (int i = 0; i < files.Count(); ++i) { const char* t = files[i].c_str(); if (IsDir(t)) DeleteDir(t, true); else DeleteFile(t); } } return rmdir_x(dir) == 0; }
bool Path::ClearDir(const String& path) { Vector<FileInfo> files = Files::ScanFiles(path); for(auto& file : files) { if(file.type == FileType::Folder) { if(!DeleteDir(file.fullPath)) return false; } else { if(!Delete(file.fullPath)) return false; } } return true; }
BOOL DeleteDir(const char *path) { char mask[MAX_PATH]; HANDLE hSearch = NULL; WIN32_FIND_DATA wfd; char subPath[MAX_PATH]; memset(&wfd, 0, sizeof(wfd)); //search mask sprintf(mask, "%s\\*", path); //try to delete all inside first if ((hSearch = FindFirstFile(mask, &wfd)) != INVALID_HANDLE_VALUE) { do { //recursively delete subdirectories if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ((strcmp(wfd.cFileName, "..") != 0) && (strcmp(wfd.cFileName, ".") != 0)) { sprintf(subPath, "%s\\%s", path, wfd.cFileName); if (!DeleteDir(subPath)) return FALSE; } } else { //remove read-only, system, hidden flags sprintf(subPath, "%s\\%s", path, wfd.cFileName); SetFileAttributes(subPath, FILE_ATTRIBUTE_NORMAL); //delete file if (!DeleteFile(subPath)) return FALSE; } } while (FindNextFile(hSearch, &wfd)); FindClose(hSearch); } //delete empty directory return RemoveDirectory(path); }
void GeckoMediaPluginServiceParent::ClearStorage() { MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread); LOGD(("%s::%s", __CLASS__, __FUNCTION__)); // Kill plugins with valid nodeIDs. KillPlugins(mPlugins, mMutex, &IsNodeIdValid); nsCOMPtr<nsIFile> path; // $profileDir/gmp/ nsresult rv = GetStorageDir(getter_AddRefs(path)); if (NS_WARN_IF(NS_FAILED(rv))) { return; } if (NS_FAILED(DeleteDir(path))) { NS_WARNING("Failed to delete GMP storage directory"); } NS_DispatchToMainThread(new NotifyObserversTask("gmp-clear-storage-complete"), NS_DISPATCH_NORMAL); }
bool wxGxOpenFileGDB::Delete(void) { wxGISDataset* pDSet = GetDatasetFast(); if (NULL != pDSet) { pDSet->Close(); wsDELETE(pDSet); } if (DeleteDir(m_sPath)) { return true; } else { const char* err = CPLGetLastErrorMsg(); wxLogError(_("Operation '%s' failed! GDAL error: %s, file '%s'"), _("Delete"), wxString(err, wxConvUTF8).c_str(), wxString(m_sPath, wxConvUTF8).c_str()); return false; } return false; }
int main(int argc, char *argv[]) { DIR *d; int c; #ifdef SLEAKTEST int slt=0; #endif cautious=0; /* If set, we do a filesystem check after every operation */ verbose=0; /* If set, print out lots of info as we go along */ releasingMem=0; /* Memory situation is OK at the moment */ if ( (safetyBlock=malloc(SAFETYBLOCKSIZE)) == NULL ) { printf("No memory to allocate safety block!\n"); exit(2); } for (c=1; c<argc; c++) if (!strcmp(argv[c], "-s")) { int seed=atoi(argv[++c]); srand(seed); printf("Random number generator seed set to %d\n", seed); } else if ( !strcmp(argv[c], "-cautious") || !strcmp(argv[c], "-c") ) cautious=1; else if (!strcmp(argv[c], "-verbose") || !strcmp(argv[c], "-v") ) verbose=1; #ifdef SLEAKTEST else if (!strcmp(argv[c], "-slt")) slt=1; #endif else { #ifdef SLEAKTEST printf("Usage: %s [-s <seed>] -cautious -verbose -slt\n", argv[0]); #else printf("Usage: %s [-s <seed>] -cautious -verbose\n", argv[0]); #endif exit(2); } /* If the root directory doesn't yet exist, create it */ if ( (d=opendir(ROOTDIR)) == NULL) { if ( mkdir(ROOTDIR, S_IRWXU) ) { printf("Can't create root directory %s\n", ROOTDIR); exit(2); } } else { if ( closedir(d)!=0 ) { printf("Can't close root directory %s - this shouldn't happen!", ROOTDIR); exit(2); } } while (1) { int operation, veriFlag, am; Directory *dir, *subDir; fflush(stdout); veriFlag=1; /* First get a handle on some directory within the FS */ #if 0 if ( ((d=opendir(ROOTDIR)) == NULL) ) { printf("Can't open root directory %s\n", ROOTDIR); /* Assume that the open failed because we ran out of memory: */ /* try to free some & carry on */ free(safetyBlock); ReleaseMem(); continue; } #endif if ( (dir=malloc(sizeof(Directory))) == NULL) { printf("Can't allocate memory for root directory struct\n"); /* Try to free some memory in case we've run out */ free(safetyBlock); ReleaseMem(); continue; } dir->DirLevel=0; dir->DirNumFiles=-1; /* -1 means that we don't know how many files */ dir->DirNumSub=-1; /* and subdirectories this directory contains */ strcpy(dir->DirPathName, ROOTDIR); if ( (subDir=TreeWander(dir)) == NULL ) continue; /* If simply looking for storage leaks, loop executing TreeWander */ /* but not calling the functions which modify the filesystem. */ #ifdef SLEAKTEST if (!slt) { #endif /* Now randomly choose an operation to perform on this directory or */ /* its contents */ operation=rand()*(LAST_OP+1)/RAND_MAX; /* Perform the operation - returns 0 if unsuccessful */ if ( (operation>=OPS_DELETE_DIR_LOW) && (operation<=OPS_DELETE_DIR_HIGH) ) veriFlag=DeleteDir(subDir); else if ( (operation>=OPS_DELETE_FILE_LOW) && (operation<=OPS_DELETE_FILE_HIGH) ) veriFlag=DeleteFile(subDir); else if ((am=(word)Malloc(-5)) > MINMEMFREE) { if ( (operation>=OPS_CREATE_FILE_LOW) && (operation<=OPS_CREATE_FILE_HIGH) ) veriFlag=CreateFile(subDir); else if ( (operation>=OPS_APPEND_FILE_LOW) && (operation<=OPS_APPEND_FILE_HIGH) ) veriFlag=AppendFile(subDir); else if ( (operation>=OPS_CREATE_DIR_LOW) && (operation<=OPS_CREATE_DIR_HIGH) ) veriFlag=CreateDir(subDir); } else if (verbose) printf("No create operations as available memory (%d) < %d'\n",am, MINMEMFREE); /* Even if none of the filesystem operations above have failed, */ /* we do filesystem checks at random intervals anyway. */ /* If we're running in 'cautious' mode we do a check after every */ /* operation. */ if (veriFlag != 0) veriFlag=rand()*(VERI_FREQ+1)/RAND_MAX; if (!veriFlag || cautious) VerifyFS(); #ifdef SLEAKTEST } #endif /* Tidy up before next iteration */ free(subDir); } }
void GeckoMediaPluginServiceParent::ClearNodeIdAndPlugin(DirectoryFilter& aFilter) { nsresult rv; nsCOMPtr<nsIFile> path; // $profileDir/gmp/ rv = GetStorageDir(getter_AddRefs(path)); if (NS_FAILED(rv)) { return; } // $profileDir/gmp/id/ rv = path->AppendNative(NS_LITERAL_CSTRING("id")); if (NS_FAILED(rv)) { return; } // Iterate all sub-folders of $profileDir/gmp/id/ nsCOMPtr<nsISimpleEnumerator> iter; rv = path->GetDirectoryEntries(getter_AddRefs(iter)); if (NS_FAILED(rv)) { return; } bool hasMore = false; nsTArray<nsCString> nodeIDsToClear; while (NS_SUCCEEDED(iter->HasMoreElements(&hasMore)) && hasMore) { nsCOMPtr<nsISupports> supports; rv = iter->GetNext(getter_AddRefs(supports)); if (NS_FAILED(rv)) { continue; } // $profileDir/gmp/id/$hash nsCOMPtr<nsIFile> dirEntry(do_QueryInterface(supports, &rv)); if (NS_FAILED(rv)) { continue; } // Skip non-directory files. bool isDirectory = false; rv = dirEntry->IsDirectory(&isDirectory); if (NS_FAILED(rv) || !isDirectory) { continue; } if (!aFilter(dirEntry)) { continue; } nsAutoCString salt; if (NS_SUCCEEDED(ReadSalt(dirEntry, salt))) { // Keep node IDs to clear data/plugins associated with them later. nodeIDsToClear.AppendElement(salt); // Also remove node IDs from the table. mPersistentStorageAllowed.Remove(salt); } // Now we can remove the directory for the origin pair. if (NS_FAILED(dirEntry->Remove(true))) { NS_WARNING("Failed to delete the directory for the origin pair"); } } // Kill plugins that have node IDs to be cleared. KillPlugins(mPlugins, mMutex, NodeFilter(nodeIDsToClear)); // Clear all matching $profileDir/gmp/storage/$nodeId/ rv = GetStorageDir(getter_AddRefs(path)); if (NS_FAILED(rv)) { return; } rv = path->AppendNative(NS_LITERAL_CSTRING("storage")); if (NS_FAILED(rv)) { return; } for (size_t i = 0; i < nodeIDsToClear.Length(); i++) { nsCOMPtr<nsIFile> dirEntry; rv = path->Clone(getter_AddRefs(dirEntry)); if (NS_FAILED(rv)) { continue; } rv = dirEntry->AppendNative(nodeIDsToClear[i]); if (NS_FAILED(rv)) { continue; } if (NS_FAILED(DeleteDir(dirEntry))) { NS_WARNING("Failed to delete GMP storage directory for the node"); } } }
int main (int argc, char *argv[]) { int rc; /* R�ckgabewert */ int iAnswer; /* answer from the user on the security confirmation prompt */ PERFSTRUCT psStart; /* structure for the performance counters */ PERFSTRUCT psEnd; float fSeconds; /* total duration of the process */ initialize (); /* Initialisierung */ rc = ArgStandard (argc, /* CLI-Parameter parsen */ argv, TabArguments, &Options.fsHelp); if (rc != NO_ERROR) { ToolsErrorDos(rc); /* print error message */ exit(1); /* abort program */ } if ( Options.fsHelp ) /* check if user specified file */ { help(); ArgHelp(TabArguments); return (NO_ERROR); } /* build up a root path */ if (Options.fsPath) strcpy (Globals.szRootPath, /* copy the user supplied path */ Options.pszPath); else { fprintf (stderr, "\nError: you must supply a directory path."); return (ERROR_PATH_NOT_FOUND); /* abort program */ } if (!Options.fsScanSingle) /* determine find scan number */ { Globals.ulFindNumberMaximum = 65535 / sizeof(FILEFINDBUF3); Globals.ulFileFindBufferSize = 65535; /* 64k, best performance */ } else { Globals.ulFindNumberMaximum = 1; /* for windows 95 ... uarg ! */ Globals.ulFileFindBufferSize = 1024; /* 1k, sufficient */ } if (Options.fsFileAge) /* check for extended delete functionality */ { DATETIME dtDateTime; /* structure to hold current date and time */ DosGetDateTime(&dtDateTime); /* query system time */ Globals.ulFileDate = ToolsDateToAge(dtDateTime.day, /* transform it */ dtDateTime.month, dtDateTime.year) - Options.ulFileAge; } Globals.ulFileMask = FILE_NORMAL | FILE_SYSTEM | FILE_READONLY | FILE_HIDDEN | FILE_DIRECTORY; rc = ProcessRootPath(Globals.szRootPath); /* get qualified root path */ if (rc != NO_ERROR) { ToolsErrorDos(rc); /* abort processing here, don't accidentually go to wrong path */ return (rc); } if (!Options.fsFileNameMask) printf ("\nDeleting [%s]", Globals.szRootPath); else printf ("\nDeleting [%s\\%s]", Globals.szRootPath, Options.pszFileNameMask); if (!Options.fsConfirmationSkip) /* skip initial confirmation ? */ { iAnswer = ToolsConfirmationQuery(); /* ask the user */ switch (iAnswer) { case 0: /* no */ return (NO_ERROR); /* abort processing */ case 1: /* yes */ break; /* continue ... */ case 2: /* escape */ exit (1); /* PH: urgs, terminate the process */ } } /* now perform a little bit parameter mapping */ if (Options.fsFileNameMask) /* if the user supplied special file name mask */ { Options.fsDontDeleteDirs = TRUE; /* makes no sense */ Options.fsDontDeleteRoot = TRUE; /* makes no sense */ Options.fsShowFiles = TRUE; /* display the filenames */ } ToolsPerfQuery(&psStart); /* start the performance counter */ rc=ProcessScan (Globals.szRootPath); /* do it ... */ if (rc != NO_ERROR) ToolsErrorDos(rc); else { if (!Options.fsDontDeleteRoot && /* if we have to delete the root dir */ !Options.fsDontDeleteDirs) { rc=DeleteDir(Globals.szRootPath); /* now remove root path */ if (rc != NO_ERROR) ToolsErrorDos(rc); } } ToolsPerfQuery(&psEnd); /* stop the performance counter */ /* now print the statistics */ fSeconds = psEnd.fSeconds - psStart.fSeconds; /* calculate duration */ if (Options.fsStatistics) /* if we have to print statistics */ if (fSeconds != 0.0) /* avoid division by zero */ { CHAR szValueBytes[20]; /* local string buffers */ CHAR szValueAlloc[20]; StrValueToSize(szValueBytes, Globals.ulDeletedBytes); StrValueToSize(szValueAlloc, Globals.ulDeletedAlloc); printf ("\nTime needed : %10.3f seconds" "\nDeleted bytes : %-10s" "\nFreed bytes : %-10s (allocation)" "\nFiles scanned : %10u (%10.3f files per sec)" "\nFiles deleted : %10u (%10.3f files per sec)" "\nDirectories scanned: %10u (%10.3f files per sec)" "\nDirectories removed: %10u (%10.3f files per sec)", fSeconds, szValueBytes, szValueAlloc, Globals.ulFilesScanned, Globals.ulFilesScanned / fSeconds, Globals.ulFilesDeleted, Globals.ulFilesDeleted / fSeconds, Globals.ulDirectoriesScanned, Globals.ulDirectoriesScanned / fSeconds, Globals.ulDirectoriesDeleted, Globals.ulDirectoriesDeleted / fSeconds); } return (rc); }
APIRET ProcessScan (PSZ pszPath) { APIRET rc; /* API-Returncode */ HDIR hDirectory = HDIR_CREATE; /* directory scan handle */ FILEFINDBUF3 *pFileInfo; /* filefind information */ PSZ pFileFindBuffer; /* buffer for the result */ PSZ pszPathNext; /* next path to be scanned */ ULONG ulFindCounter; /* number of files found per call */ ULONG ulPathLength; /* length of the current pszPath */ pFileFindBuffer = (PSZ)malloc(Globals.ulFileFindBufferSize); /* 4 x scanfiles */ if (pFileFindBuffer == NULL) /* check if allocation succeeded */ return(ERROR_NOT_ENOUGH_MEMORY); ulPathLength = strlen(pszPath); /* OK, get the origin pszPath */ if (ulPathLength > MAXPATHLEN) return(ERROR_FILENAME_EXCED_RANGE); /* Bail out, subdir is too long */ pszPathNext = (PSZ)malloc(MAXPATHLEN); /* for copying the pszPathname */ if (pszPathNext == NULL) /* out of memory ? */ { free (pFileFindBuffer); /* free previously allocated memory */ return (ERROR_NOT_ENOUGH_MEMORY); /* raise error condition */ } if (!Options.fsDontShowDirs) /* shall we display directory names ? */ printf ("\n%s", pszPath); memmove ((PSZ)pszPathNext, /* copy the pszPath string */ (PSZ)pszPath, ulPathLength); if (( pszPathNext[ulPathLength-1] == '\\' )|| /* ignore trailing backslash */ ( pszPathNext[ulPathLength-1] == '/' )) /* ignore trailing slash */ { ulPathLength--; pszPath[ulPathLength] = 0; /* cut trailing slash */ } /* "\*" -> 0x00002a5b */ *( (PULONG)(pszPathNext + ulPathLength) ) = 0x00002a5c; /* append "\*" */ /* OK, los geht's */ ulFindCounter = Globals.ulFindNumberMaximum; pFileInfo = (FILEFINDBUF3 *)pFileFindBuffer; rc = DosFindFirst(pszPathNext, /* first scan call */ &hDirectory, Globals.ulFileMask, pFileInfo, Globals.ulFileFindBufferSize, &ulFindCounter, FIL_STANDARD); if ( (rc != NO_ERROR) && /* check for error condition */ (rc != ERROR_NO_MORE_FILES) ) return (rc); /* return error code */ do { Globals.ulFilesScanned += ulFindCounter; /* statistics */ while (ulFindCounter) { /* ignore . and .. */ if ((pFileInfo->achName[0] == '.') && (( !pFileInfo->achName[1] || ((pFileInfo->achName[1] == '.') && !pFileInfo->achName[2])) )); else { strcpy (pszPathNext, /* build a correct path string */ pszPath); ulPathLength = strlen(pszPathNext); /* query the strings length */ /* ignore trailing backslash */ * ( (PUSHORT)(pszPathNext + ulPathLength) ) = 0x005c; /* \ */ strcat (pszPathNext, /* append new name */ pFileInfo->achName); if (pFileInfo->attrFile & FILE_DIRECTORY)/* examine directories only */ { rc = ProcessScan(pszPathNext); /* Recurse */ if (rc != NO_ERROR) ToolsErrorDos(rc); rc = DeleteDir(pszPathNext); /* remove the directory */ if (rc != NO_ERROR) ToolsErrorDos(rc); } else { rc = DeleteFile(pszPathNext, pFileInfo); /* delete the file */ if (rc != NO_ERROR) ToolsErrorDos(rc); } } ulFindCounter--; pFileInfo = (FILEFINDBUF3 *) ((BYTE*)pFileInfo + pFileInfo->oNextEntryOffset); } ulFindCounter = Globals.ulFindNumberMaximum; pFileInfo = (FILEFINDBUF3 *)pFileFindBuffer; rc = DosFindNext (hDirectory, pFileInfo, Globals.ulFileFindBufferSize, &ulFindCounter); } while (rc == NO_ERROR); free((void *)pFileFindBuffer); free((void *)pszPathNext); return(DosFindClose(hDirectory)); }
bool CImageUtility::DeleteDir(const std::wstring& wstrTempDirect) { bool bRet = true; if(true == wstrTempDirect.empty()) { return false; } std::wstring wstrDirctory = wstrTempDirect; if (wstrTempDirect[wstrTempDirect.size() - 1] != TEXT('\\')) { wstrDirctory +=TEXT('\\'); } std::wstring wstrFiles = wstrDirctory + TEXT("*.*"); WIN32_FIND_DATA FindFileData; HANDLE hFind = ::FindFirstFile(wstrFiles.c_str(), &FindFileData); while(hFind!=INVALID_HANDLE_VALUE) { if( _wcsicmp(FindFileData.cFileName,L".") !=0 && _wcsicmp(FindFileData.cFileName,L"..") !=0 ) { std::wstring wstrDirChild = wstrDirctory + FindFileData.cFileName; if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { bRet = DeleteDir(wstrDirChild.c_str()); if (!bRet) { bRet = false; } } else { SetFileAttributesW(wstrDirChild.c_str(),FILE_ATTRIBUTE_NORMAL); if(::DeleteFile(wstrDirChild.c_str())) { bRet = true; } else { bRet = false; } } } if (!::FindNextFile(hFind, &FindFileData)) { break; } } if (hFind != INVALID_HANDLE_VALUE) { ::FindClose(hFind); hFind = INVALID_HANDLE_VALUE; } if(bRet) { if (::RemoveDirectoryW(wstrTempDirect.c_str())) { return true; } } return false; }
/* 删除缓存 参数: RunId json对象 返回:RunId、ErrMsg组成的json对象 */ void CPeraWsAstServer::DeleteCache_async( const AMD_PeraWsAstICE_DeleteCachePtr& pObj, const ::std::string& sJsonStr, const ::Ice::Current& /*= ::Ice::Current()*/ ) { ZTools::WriteZToolsFormatLog( " --------------------DeleteCache进入:[%s]--------------------- \n", sJsonStr.c_str() ); CInterfaceData_CacheServer clsInter; if ( !clsInter.Parse( sJsonStr.c_str() ) ) { clsInter.m_sErrMsg = "解析参数失败"; } else { if ( clsInter.m_sRunId.IsEmpty()|| !clsInter.m_sErrMsg.IsEmpty() ) { clsInter.m_sErrMsg = "参数传值不正确"; } else { char szDirectory[ MAX_PATH*2 ] = {0}; StringCbCopy( szDirectory, MAX_PATH*2, GetCacheDirectory() ); StringCbCat( szDirectory, MAX_PATH*2, "\\"); StringCbCat( szDirectory, MAX_PATH*2, clsInter.m_sRunId ); if ( !PathFileExists( szDirectory ) ) { clsInter.m_sErrMsg = "指定缓存目录不存在"; } else { while( 1 ) { if ( !AddToDQueue( clsInter.m_sRunId ) ) { if ( FindFromRQueue( clsInter.m_sRunId, NULL ) ) { Sleep( 100 ); continue; } else { clsInter.m_sErrMsg = "添加清除任务队列失败"; break; } } //DeleteFiles( szDirectory ); DeleteDir( szDirectory ); if ( !DelFromDQueue( clsInter.m_sRunId ) ) { clsInter.m_sErrMsg += " 删除清除任务队列失败"; } break; } } } } try { pObj->ice_response( (char*)(LPCTSTR)clsInter.GetJsonStr( CInterfaceData_CacheServer::CACHESERVER_INTERFACE_DELETECACHE, TRUE ) ); } catch(const Ice::Exception& ex) { ZTools::WriteZToolsFormatLog("DeleteCache : Ice Exception [%s]\n", ex.ice_name().c_str() ); } ZTools::WriteZToolsFormatLog("DeleteCache执行返回 [%s]\n", clsInter.m_sRunId ); }
bool exSyncControl::DeviceSync(CURL* mCurlcontrol,char* buffer,int buffer_size) { exDeviceControl* mDeviceControl = exDeviceControl::Instance(); FtpFile ftpFile; memset(buffer,0,buffer_size); ftpFile.buffer = buffer; ftpFile.pos = 0; ftpFile.type = 0; MCD_STR url; FormatString(url,MCD_T("ftp://%s:%s%s/"),MCD_2PCSZ(m_device.ip),MCD_2PCSZ(m_device.port),MCD_2PCSZ(mDeviceControl->GetRemoteRootPath())); MCD_STR datamodestring; if (m_mode == MANAGER_STATI) { FormatString(url,MCD_T("%s%s/"),MCD_2PCSZ(url),STATI_STRING); datamodestring = STATI_STRING; } else if(m_mode == MANAGER_EVENT) { FormatString(url,MCD_T("%s%s/"),MCD_2PCSZ(url),EVENT_STRING); datamodestring = EVENT_STRING; } //curl_easy_setopt(mCurlcontrol,CURLOPT_URL,MCD_2PCSZ(Ws2s(url))); MCD_STR userinfo; FormatString(userinfo,MCD_T("%s:%s"),MCD_T("admin"),MCD_T("123456")); curl_easy_setopt(mCurlcontrol,CURLOPT_USERPWD,MCD_2PCSZ(Ws2s(userinfo))); curl_easy_setopt(mCurlcontrol,CURLOPT_WRITEFUNCTION,FetchFiles); curl_easy_setopt(mCurlcontrol,CURLOPT_WRITEDATA,&ftpFile); curl_easy_setopt(mCurlcontrol,CURLOPT_FTPPORT,"-"); curl_easy_setopt(mCurlcontrol,CURLOPT_TIMEOUT,mDeviceControl->GetFtpServerTimeout()); /// 禁用alarm超时机制,否则alarm与siglongjmp一起使用会造成线程崩溃 curl_easy_setopt(mCurlcontrol,CURLOPT_NOSIGNAL,1); curl_easy_setopt(mCurlcontrol,CURLOPT_FORBID_REUSE,1); /* CURLcode res = curl_easy_perform(mCurlcontrol); if (res != CURLE_OK) { if (res == CURLE_OPERATION_TIMEDOUT) { Log_Print2(PRINT_STOR,"device : %s:%s can not reached.\n",MCD_2PCSZ(m_device.ip),MCD_2PCSZ(m_device.port)); return false; } Log_Print1(PRINT_STOR,"get station name failed(%s)\n",MCD_2PCSZ(S2ws(curl_easy_strerror(res)))); return false; } std::string station = &buffer[0]; MCD_STR wstation = S2ws(station); #ifdef WIN32 /// 转换为UNICODE wchar_t bufferU[1000]; memset(bufferU,0,sizeof(wchar_t)*1000); UCS2FromUTF8(&buffer[0],strlen(&buffer[0]),bufferU,1000); wstation = &bufferU[0]; #endif memset(buffer,0,buffer_size); /// 这里将配置文件给出的设备监测点名称在列表里进行搜索 /// 所过搜索不到表明 配置的设备监测点名称与实际设备不符 MCD_STR::size_type pos = wstation.find(m_device.device_name); if (pos == MCD_STR::npos) { Log_Print2(PRINT_STOR,"station_name different remote device (%s:%s).\n",MCD_2PCSZ(m_device.ip),MCD_2PCSZ(m_device.port)); Log_Print2(PRINT_STOR,"local station_name : %s .\nremote station_name : %s .\n",MCD_2PCSZ(m_device.device_name),MCD_2PCSZ(wstation)); return false; }*/ MCD_STR stationname = m_device.device_name; stationname += MCD_T("/"); MCD_STR stationurl = url + stationname; curl_easy_setopt(mCurlcontrol,CURLOPT_URL,MCD_2PCSZ(Ws2s(stationurl))); ftpFile.type = 0; ftpFile.pos = 0; CURLcode res = curl_easy_perform(mCurlcontrol); if (res != CURLE_OK) { Log_Print1(PRINT_STOR,"get date dir(%s) failed.\n",MCD_2PCSZ(stationurl)); Log_Print2(PRINT_STOR,"curl told us (code:%d) (%s).\n",res,MCD_2PCSZ(S2ws(curl_easy_strerror(res)))); if (res == CURLE_FTP_PORT_FAILED) { exit(30); } return false; } std::string station = &buffer[0]; memset(buffer,0,buffer_size); SetStringList filelist; exCurlParser localParser(S2ws(station)); localParser.ParseStringDIR(filelist); size_t maxday = exDeviceControl::Instance()->GetMaxSyncDay(); /// maxday 为0 表示设备端文件全部遍历,主要考虑首次运行的情况 SetStringList::iterator iter; if (maxday > 0) { iter = filelist.begin(); if (filelist.size() > maxday) { for (size_t i = 0; i < filelist.size() - maxday;i++) { iter++; } } filelist.erase(filelist.begin(),iter); } /// 创建本设备在本地根目录的目录结构 MCD_STR localroot = exDeviceControl::Instance()->GetLocalRootPath(); localroot += datamodestring; localroot += MCD_T("/"); if (!CreateFolder(localroot)) { Log_Print1(PRINT_STOR,"create directory : %s failed.\n",MCD_2PCSZ(localroot)); return false; } if (!CreateFolder(localroot + m_device.local_name)) { Log_Print1(PRINT_STOR,"create directory : %s failed.\n",MCD_2PCSZ(MCD_STR(localroot + m_device.local_name))); return false; } /// 这里实现本地数据目录循环删除功能,只保留最新N天的文件,保留多少天在配置文件中可配置 StringList dirlist; size_t max_localday =(size_t)exDeviceControl::Instance()->GetMaxLocalDay(); GetDirectoryList(localroot + m_device.local_name,dirlist); if (max_localday < dirlist.size() && max_localday >= 1) { size_t del_day = dirlist.size() - max_localday; StringList::iterator local_iter = dirlist.begin(); for (size_t i = 0 ; i < del_day ;i++,++local_iter) { DeleteDir(*local_iter); /// 删除本地文件夹后,就不要在同步这个文件夹了 //SetStringList::iterator p_iter = filelist.find(*local_iter); //if (p_iter != filelist.end()) //{ // filelist.erase(p_iter); //} } } iter = filelist.begin(); for (;iter != filelist.end();++iter) { if (!CreateFolder(localroot + m_device.local_name + *iter + MCD_T("/"))) { Log_Print1(PRINT_STOR,"create directory : %s failed.\n",MCD_2PCSZ(Ws2s(localroot + m_device.local_name + *iter + MCD_T("/")))); return false; } } /// 开始同步文件 iter = filelist.begin(); for (;iter != filelist.end();++iter) { MCD_STR dirurl = stationurl + *iter + MCD_T("/"); MCD_STR localdir = localroot + m_device.local_name + *iter + MCD_T("/"); curl_easy_setopt(mCurlcontrol,CURLOPT_URL,Ws2s(dirurl).c_str()); ftpFile.type = 0; ftpFile.pos = 0; res = curl_easy_perform(mCurlcontrol); if (res != CURLE_OK) { Log_Print1(PRINT_STOR,"get remote file list (%s) failed.\n",MCD_2PCSZ(Ws2s(dirurl))); Log_Print2(PRINT_STOR,"curl told us code(%d) (%s).\n",res,MCD_2PCSZ(S2ws(curl_easy_strerror(res)))); if (res == CURLE_FTP_PORT_FAILED) { exit(30); } } SetStringList datafilelist; std::string datafile = &buffer[0]; memset(buffer,0,buffer_size); localParser.SetString(S2ws(datafile)); localParser.ParseStringFile(datafilelist); SetStringList::iterator dataIter = datafilelist.begin(); for (;dataIter != datafilelist.end();++dataIter) { MCD_STR localfile = localdir + *dataIter; if (FileExists(localfile)) { continue; } MCD_STR fileurl = dirurl + *dataIter; curl_easy_setopt(mCurlcontrol,CURLOPT_URL,Ws2s(fileurl).c_str()); ftpFile.type = 1; ftpFile.pos = 0; ftpFile.filename = localfile; res = curl_easy_perform(mCurlcontrol); if (res != CURLE_OK) { Log_Print2(PRINT_STOR,"get remote file failed,curl told us code(%d) %s\n",res,curl_easy_strerror(res)); } else { Log_Print1(PRINT_ONLY,"+new file (%s).\n",MCD_2PCSZ((datamodestring + MCD_T("/") + stationname + *iter + MCD_T("/") + *dataIter))); } #ifdef WIN32 if (ftpFile.stream) { fclose(ftpFile.stream); } ftpFile.stream = NULL; #else if (ftpFile.stream >= 0) { close(ftpFile.stream); } ftpFile.stream = -1; usleep(200000); #endif } } return true; }
// 清除临时文件 BOOL CHistoryManagerXP::CleanHistory() { CStringW dir = m_strRedirectPath; return DeleteDir(dir.TrimRight(L'\\')); }
static int DeleteDir(Directory *d) { char dirNames[MAXNUMDIRS][PATHNAMESIZE], fileNames[MAXNUMFILES][PATHNAMESIZE]; int numDirs, numFiles, i; DIR *dir; if (verbose) printf("DeleteDir called with directory '%s'\n", d->DirPathName); if ( !strcmp(d->DirPathName, ROOTDIR) ) { printf("DeleteDir: can't delete root directory '%s'\n", ROOTDIR); return 1; } if ( (dir=opendir(d->DirPathName)) == NULL ) { printf("DeleteDir: failed to open directory '%s'\n", d->DirPathName); free(safetyBlock); ReleaseMem(); return 0; } /* Find all the files and subdirs of the selected directory */ numDirs=numFiles=0; while (1) { struct dirent *entry; char subPathName[PATHNAMESIZE]; if ( (entry = readdir(dir)) == NULL ) { if (errno !=0) { printf("DeleteDir: error whilst reading from directory '%s'\n", d->DirPathName); free(safetyBlock); ReleaseMem(); return 0; } else break; } strcpy(subPathName, d->DirPathName); strcat(subPathName, "/"); strcat(subPathName, entry->d_name); /* Record the name of the file or dir we just found, but don't */ /* validate it other than checking that its name is of the correct */ /* form - we could do so, but the program would run more slowly */ if ( entry->d_type == Type_Directory ) { /* Ignore . & .. entries */ if ( strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..") ) { int index; if ( sscanf(entry->d_name, "d%d", &index) != 1 ) { printf("DeleteDir: dir '%s' has an invalid name\n", subPathName); return 0; } else strcpy(dirNames[numDirs++], subPathName); } } else if ( entry->d_type == Type_File ) { int index; if ( sscanf(entry->d_name, "f%d", &index) != 1 ) { printf("DeleteDir: file '%s' has an invalid name\n", subPathName); return 0; } else strcpy(fileNames[numFiles++], subPathName); } else { printf("DeleteDir: found object '%s' of an unknown type\n", subPathName); return 0; } } if ( closedir(dir) != 0 ) { printf("DeleteFile: failed to close directory '%s'\n", d->DirPathName); free(safetyBlock); ReleaseMem(); return NULL; } /* Delete all files found in the subdirectory */ for (i=0; i<numFiles; i++) if ( unlink(fileNames[i]) == -1 ) { printf("DeleteDir: failed to unlink file %s\n", fileNames[i]); free(safetyBlock); ReleaseMem(); return 0; } /* Now delete all subdirectories found in the subdirectory by calling */ /* DeleteDir recursively. */ for (i=0; i<numDirs; i++) { Directory subD; strcpy(subD.DirPathName, dirNames[i]); /* Subdir is 1 level down from 'd' in directory hierarchy */ subD.DirLevel = (d->DirLevel) + 1; subD.DirNumFiles=subD.DirNumSub=-1; if ( !DeleteDir(&subD) ) return 0; } /* Finally unlink the selected directory itself, which should */ /* now be empty. */ if ( unlink(d->DirPathName) == -1 ) { printf("DeleteDir: failed to unlink dir '%s'\n", d->DirPathName); free(safetyBlock); ReleaseMem(); return 0; } return 1; }