GetTempFileName 似乎已在 Windows 10 上损坏

GetTempFileName appears to be broken on Windows 10

我有一个使用 GetTempFileName 的 MFC 程序。在 Windows 7 上它工作正常,但是当我将相同的代码用于 Windows 10 时它会产生垃圾。

TCHAR temp_dir[1024];
GetTempPath(1024,temp_dir);
TCHAR temp_file[1024];
GetTempFileName("C:\","udb",0,temp_file);
std::cout << "Temp DB Path: " << temp_file << std::endl;

在 Windows7:

Temp DB Path: C:\udb2145.tmp

在 Windows10:

Temp DB Path: o▒

我的代码是不是做错了什么?或者我应该使用其他功能吗?

嗯,首先,当我测试你的例子时,GetTempFileName returns 0,这意味着它遇到了一个错误(return成功的值是非零临时文件标识符) . GetLastError returns -5,这意味着:"Access Denied",我非常怀疑非管理应用程序可以写入 "C:\"(至少在 Windows 8+ 下)。

您看到的正在打印的垃圾值是因为您没有初始化 temp_file 数组。你应该这样做:

TCHAR temp_file[1024] = {0};

并且,为了让您的代码正常工作,请将临时文件存储在实际的临时文件夹中:

GetTempFileName(temp_dir,"udb",0,temp_file);

编辑:并且,正如其中一位评论者已经指出的那样,如果您的代码使用 unicode,您将需要 wcout 才能正确输出文件名。否则您将只能看到文件路径的第一个字符。但这会影响到控制台的输出。