C++ - How to get the user folder?

半城伤御伤魂 提交于 2021-01-03 06:00:47

问题


I'm having a little problem with my program...

I have to create a file with the application data, but I don't know how to access the %USER% or %APPDATA% directories...

I've tried to use the application folder, but if I install the application in D:\Program Files\(Organization)\(APPName) I cannot write new files in this directory, I can just read or modify if I don't have admin privileges...

So, the question is: How to access the %USER% folder or Get ADMIN privileges with the application... PS.: I'm using VCL in C++ Builder


回答1:


One classic way is to read the environment variables using getenv:

char *user = getenv("USER");
char *appdata = getenv("APPDATA");

Regarding user rights and performing file read/write/create in these locations, you certainly can in the user folder the application is running as. In other folders, you'll need to run it as either the target user or administrator. Also, after installing an application in Program Files or Program Files (x86), the system will not allow you to write there. Installations are performed under the 'trustedinstaller' user credentials and the final user rights are set during installation for 'current user' or 'all users'.

Hope this helps.




回答2:


Assuming this is a pure Windows question, you should use SHGetSpecialFolderPath.

  • Pass CSIDL_PROFILE to get the equivalent of %USERPROFILE%.
  • Pass CSIDL_APPDATA to get the equivalent of %APPDATA%.

Note that the documentations for the CSIDL based functions are a little scary in that they talk about function not being supported or deprecated. Instead they urge you to use SHGetKnownFolderPath. That's fine if your program never needs to run on XP. If that's the case, go ahead and use SHGetKnownFolderPath. Otherwise, use the CSIDL based options.



来源:https://stackoverflow.com/questions/21428407/c-how-to-get-the-user-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!