如何将特定Windows用户路径替换为正在运行的用户

How to Replace Specific Windows Username Path with The User Running

本文关键字:用户 运行 替换 路径 Windows      更新时间:2023-10-16

所以我要做的是让路径中的用户名是它运行的用户名

例如,如果我正在运行这个程序的Windows用户名为Bob,那么我想在Bob的桌面上创建这个文件。而不是代码中设置的那个

我已经尽力解释清楚了,谢谢。

#include <fstream>
#include <ostream>
using namespace std;
int main()
{
  std::ofstream fs("C:\Users/SAMPLE_USERNAME/Desktop/omg it works.txt"); //makes the text file
  fs<<"Testing this thing!"; //writes to the text file
  fs.close();
  return 0;
}

我使用Code::Blocks,如果有帮助的话。

既然你提到了一个Windows用户,我假设你我想要一个Windows的解决方案。可以获取用户名使用Win32函数SHGetKnownFolderPath。但是,请注意如果你想让你的应用程序支持Windows XP,那么你可以这么做必须使用旧的(已弃用的)函数SHGetFolderPath。你可以使用这个示例:

wchar_t *pszDesktopFolderPath;
if(S_OK == SHGetKnownFolderPath(FOLDERID_Desktop, KF_FLAG_DEFAULT, NULL, pszDesktopFolderPath))
{
    // pszDesktopFolderPath now points to the path to desktop folder
    ...
    // After you are done with it, delete the buffer for the path like this
    CoTaskMemFree(pszDesktopFolderPath);
}

这里是一个使用SHGetFolderPath的例子:

LPTSTR pszDesktopFolderPath[MAX_PATH];
if(S_OK == SHGetFolderPathA(NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, pszDesktopFolderPath))
{
    // pszDesktopFolderPath now points to the path to desktop folder, no need to manually release memory
}

请注意,第三个参数表示用户的令牌试图获取桌面位置。当你的应用程序是由将权限从标准用户帐户提升到管理员帐户,上述函数返回的路径是到桌面的路径管理员用户的。如果您想获得标准用户的路径,您可以必须获取该用户的令牌并将其作为第三个参数传递。