Using Windows Environment Variable in Native Code

2019-07-20 21:48发布

// 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?

2条回答
forever°为你锁心
2楼-- · 2019-07-20 22:06

try using the GetEnvironmentVariable function

查看更多
倾城 Initia
3楼-- · 2019-07-20 22:16

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

See:

http://msdn.microsoft.com/en-us/library/ms724265(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/bb762275(v=vs.85).aspx

查看更多
登录 后发表回答