saz*_*azr 2 c++ winapi temporary-files
我的C++ winAPI应用程序需要在将文件上载到服务器之前创建临时文件.所以我已经搜索了创建临时文件的方法,并发现有很多方法可以做到这一点.
你能否告诉我:对于以下每种方法,在哪种情况下我应该使用该方法?哪种方法最能满足我的需求?
方法1:
// Using CreateFile()
CreateFile( "myfile.txt", GENERIC_ALL, ..., FILE_ATTRIBUTE_TEMPORARY, 0); // removed unecessary parameters
Run Code Online (Sandbox Code Playgroud)
方法2:
// I think that GetTempFileName also creates the file doesn't it? Not just generates a unique fileName?
// Gets the temp path env string (no guarantee it's a valid path).
dwRetVal = GetTempPath(MAX_PATH, // length of the buffer
lpTempPathBuffer); // buffer for path
// Generates a temporary file name.
uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files
TEXT("DEMO"), // temp file name prefix
0, // create unique name
szTempFileName); // buffer for name
Run Code Online (Sandbox Code Playgroud)
方法3:
// Create a file & use the flag DELETE_ON_CLOSE. So its a temporary file that will delete when the last HANDLE to it closes
HANDLE h_file = CreateFile( tmpfilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL );
Run Code Online (Sandbox Code Playgroud)
为什么创建临时文件的方法不止一种.并且,例如,我想要使用方法2而不是方法1的情况是什么?
FILE_ATTRIBUTE_TEMPORARY 如果有足够的缓存,只是告诉Windows不要把文件内容写入磁盘,因为该文件是临时的,没有其他进程会使用它.
FILE_FLAG_DELETE_ON_CLOSE意味着它所说的 - 当您关闭文件时,它将被自动删除.这保证了它是暂时的.
GetTempFilename 为临时文件创建名称,并保证先前未使用过文件名.
创建临时文件时应使用所有3种方法.他们都不会干扰其他人.