我正在尝试创建一个简单的控制台应用程序,只清理%temp%文件。那么,如何在临时文件目录中找到用户名和系统盘进行输入呢?
这是一个字符串变量,我计划在其中存储%temp%目录:
string tempDir = sysDisk << ":/Users/" << userName << "AppData/Local/Temp/"发布于 2021-07-16 00:35:13
你做的这一切都错了。您根本不需要检索系统盘或用户名。特别是因为%temp%文件夹的位置是user-defined,所以不能保证它位于您尝试创建的路径中。而且Windows的USERS和TEMP文件夹的位置已经随着时间的推移而改变了,所以将来可能还会改变。
正确的解决方案是询问操作系统用户的实际%temp%文件夹当前所在的确切位置。
例如,通过使用以下任一方法:
#include <cstdlib>
std::string tempDir = std::getenv("TEMP");#include <filesystem>
std::string tempDir = std::filesystem::temp_directory_path().string();或者,使用Win32应用编程接口函数:
#include <windows.h>
char path[MAX_PATH] = {};
DWORD len = GetTempPath(path, MAX_PATH);
std::string tempDir(path, len);#include <windows.h>
char path[MAX_PATH] = {};
DWORD len = GetEnvironmentVariable("TEMP", path, MAX_PATH);
std::string tempDir(path, len);#include <windows.h>
char path[MAX_PATH] = {};
DWORD len = ExpandEnvironmentStrings("%TEMP%", path, MAX_PATH);
std::string tempDir(path, len-1);
// This would be useful when dealing with individual filenames, eg:
// ExpandEnvironmentStrings("%TEMP%\filename.ext", path, MAX_PATH);https://stackoverflow.com/questions/68396672
复制相似问题