c++ - 创建临时文件 : can't write to it

标签 c++ winapi

每当我在 C++ Native WinAPI 中创建临时文件时,返回的 HANDLE 总是 INVALID_FILE_HANDLE 但临时文件已正确创建?

我做错了什么吗?

如果我使用 GetLastError() 输出是:

"The file exists"

在我下面的代码中,我可以成功创建一个临时文件,但 CreateFile 函数总是返回 INVALID_FILE_HANDLE,我无法向文件句柄写入任何文本:

GetTempPath(dirLen, dir);
GetTempFileName(dir, fName, 0, tName);
HANDLE file = CreateFile(tName, GENERIC_WRITE, 0, NULL, CREATE_NEW,
                         FILE_ATTRIBUTE_TEMPORARY, NULL);
if (file == INVALID_HANDLE_VALUE) {
   outputLastError(); // Outputs: "The file exists"
}

if (FAILED(WriteFile(file, (LPTSTR)toWrite.c_str(), strLen, 0, NULL))) {
   cout << (_T("Failed to write string to file \r\n"));
   outputLastError();
   res = false;
}

// WriteFile doesn't fail but the temporary file is empty when I open it?

最佳答案

GetTempFileName()将始终创建文件:

If uUnique is zero, the function attempts to form a unique file name using the current system time. If the file already exists, the number is increased by one and the functions tests if this file already exists. This continues until a unique filename is found; the function creates a file by that name and closes it. Note that the function does not attempt to verify the uniqueness of the file name when uUnique is nonzero.

CREATE_NEW 然后在 CreateFile() 中指定(正如 Mat 已经指出的)导致 CreateFile() 返回 INVALID_FILE_HANDLE:

CREATE_NEW Creates a new file, only if it does not already exist. If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80). If the specified file does not exist and is a valid path to a writable location, a new file is created.

关于c++ - 创建临时文件 : can't write to it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10614406/

相关文章:

c++ - 坐标排序

c++ - 防止将一个 Sprite 移动到另一个 Sprite 上

c++ - system() 函数找不到可执行文件的可能原因是什么?

c++ - 在 Windows 服务中使用命名管道时出现问题

c - 要传递给 CreateDIBSection 函数的参数

c++ - 控制台内容

c++ - win32 : WM_PAINT calls but not supposed to be!

c++ - "reference can never be made to refer to another object"是什么意思?

c++ - 您可以使用哪些技术来分析您的代码

c++ - 使用插件更改 C++ 应用程序中的默认行为