gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:53:30 25 4
gpt4 key购买 nike

每当我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com