Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Windows Environment Variable in Native Code

// I have a permission to create a file to Program Files
const std::wstring sFileName = L"%ProgramFiles%\\aaa.txt";
HANDLE h = CreateFileW(
  sFileName.c_str(),
  GENERIC_READ,
  FILE_SHARE_DELETE,
  0,
  CREATE_ALWAYS,
  0,
  0);
// INVALID_HANDLE_VALUE with ERROR_PATH_NOT_FOUND

I expected it makes C:\Program Files\aaa.txt or C:\Program Files (x86)\aaa.txt depend on the Os' environment. But it didn't work.
What's wrong? How do I use environment variable in native code?

like image 801
Benjamin Avatar asked Mar 22 '26 20:03

Benjamin


1 Answers

You need to explicitly expand the environment variables. One way is using the Win32 API's ExpandEnvironmentStrings or ExpandEnvironmentStringsForUser

like image 188
Robert Horvick Avatar answered Mar 25 '26 13:03

Robert Horvick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!