0

I am trying to create a simple console app, that just cleans %temp% files. So, how can I find the username and system disk to input it in directory of temp files?

This is a string variable, where I plan to store the %temp% directory:

string tempDir = sysDisk << ":/Users/" << userName << "AppData/Local/Temp/"
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

0

You are going about this all wrong. You don't need to retrieve the system disk or username at all. Especially since the location of the %temp% folder is user-defined, so there is no guarantee that it is even located at the path you are trying to create. And also that the location of Windows' USERS and TEMP folders have changed over time, and so may change again in the future.

The correct solution is to ask the OS exactly where the user's actual %temp% folder is currently located.

For instance, by using either:

#include <cstdlib>
std::string tempDir = std::getenv("TEMP");
#include <filesystem>
std::string tempDir = std::filesystem::temp_directory_path().string();

Or, using Win32 API functions:

#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);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770