在本地代码中使用Windows环境变量 [英] Using Windows Environment Variable in Native Code
问题描述
const std :: wstring sFileName = L%ProgramFiles%\\\aaaa。
HANDLE h = CreateFileW(
sFileName.c_str(),
GENERIC_READ,
FILE_SHARE_DELETE,
0,
CREATE_ALWAYS,
0,
0);
// INVALID_HANDLE_VALUE with ERROR_PATH_NOT_FOUND
我预计它会使 C:\Program Files \aaa.txt 或 C:\Program文件(x86)\aaa.txt 取决于Os的环境。但它没有工作。
怎么了?如何在本地代码中使用环境变量?
您需要显式扩展环境变量。一种方法是使用Win32 API的ExpandEnvironmentStrings或ExpandEnvironmentStringsForUser
请参阅:
http://msdn.microsoft.com/en-us/library/ms724265(v = vs85).aspx
http://msdn.microsoft.com/en-us/library/bb762275(v = vs85).aspx
// 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?
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
这篇关于在本地代码中使用Windows环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!