|
| 1 | +//#include <fileapi.h> |
| 2 | +//#include <WinBase.h> //FILE_FLAG_DELETE_ON_CLOSE |
| 3 | +#include <windows.h> //https://stackoverflow.com/questions/4845198/fatal-error-no-target-architecture-in-visual-studio |
| 4 | +#include <io.h> //_open_osfhandle |
| 5 | +#include <fcntl.h> //_O_RDONLY, _O_WRONLY |
| 6 | +#include <stdio.h> |
| 7 | + |
| 8 | +//https://stackoverflow.com/questions/12249610/c-create-file-in-memory |
| 9 | +//https://docs.microsoft.com/zh-tw/windows/win32/fileio/creating-and-using-a-temporary-file |
| 10 | +FILE* createTempFile() { |
| 11 | + TCHAR szTempFileName[MAX_PATH] = { 0 }; |
| 12 | + TCHAR lpTempPathBuffer[MAX_PATH] = { 0 }; |
| 13 | + |
| 14 | + DWORD dwRetVal = GetTempPath(MAX_PATH, // length of the buffer |
| 15 | + lpTempPathBuffer); |
| 16 | + if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { |
| 17 | + printf("GetTempPath failed\n"); |
| 18 | + return NULL; |
| 19 | + } |
| 20 | + //wprintf(L"temp path: %s\n", lpTempPathBuffer); |
| 21 | + //temp path: C:\Users\xxx\AppData\Local\Temp\ |
| 22 | +
|
| 23 | + UINT uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files |
| 24 | + TEXT("DEMO"), // temp file name prefix |
| 25 | + 0, // create unique name |
| 26 | + szTempFileName); // buffer for name |
| 27 | + if (uRetVal == 0) { |
| 28 | + printf("GetTempFileName failed\n"); |
| 29 | + return NULL; |
| 30 | + } |
| 31 | + //wprintf(L"temp name: %s\n", szTempFileName); |
| 32 | + //temp name: C:\Users\xxx\AppData\Local\Temp\DEM6C25.tmp |
| 33 | + |
| 34 | + HANDLE hTempFile = CreateFile((LPTSTR)szTempFileName, // file name |
| 35 | + GENERIC_READ | GENERIC_WRITE, // open for write |
| 36 | + 0, // do not share |
| 37 | + NULL, // default security |
| 38 | + CREATE_ALWAYS, // overwrite existing |
| 39 | + FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,// normal file |
| 40 | + NULL); // no template |
| 41 | + |
| 42 | + //https://stackoverflow.com/questions/5193579/how-make-file-from-handle-in-winapi |
| 43 | + int nHandle = _open_osfhandle((long)hTempFile, _O_RDONLY | _O_WRONLY); |
| 44 | + if (nHandle == -1) { |
| 45 | + ::CloseHandle(hTempFile); //case 1 |
| 46 | + return nullptr; |
| 47 | + } |
| 48 | + FILE* fp = _fdopen(nHandle, "w+"); |
| 49 | + if (!fp) { |
| 50 | + ::CloseHandle(hTempFile); //case 2 |
| 51 | + } |
| 52 | + return fp; |
| 53 | +} |
| 54 | + |
| 55 | +int main() { |
| 56 | + FILE* fp = createTempFile(); |
| 57 | + |
| 58 | + char buffer[] = { 'H','e','l', 'l','o' }; |
| 59 | + if (fp == NULL) { |
| 60 | + printf("open failure"); |
| 61 | + return 1; |
| 62 | + } |
| 63 | + fwrite(buffer, 1, sizeof(buffer), fp); |
| 64 | + fflush(fp); |
| 65 | + fclose(fp); |
| 66 | + return 0; |
| 67 | +} |
0 commit comments