【问题标题】:How to Replace Specific Windows Username Path with The User Running如何用正在运行的用户替换特定的 Windows 用户名路径
【发布时间】:2016-11-03 06:18:27
【问题描述】:

所以我想要做的是让路径中的用户名成为它所运行的任何用户。

例如,如果我在其下运行此程序的 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。

【问题讨论】:

标签: c++


【解决方案1】:

既然您提到了 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

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2018-06-27
    • 2015-11-02
    • 2014-06-09
    • 2016-01-14
    相关资源
    最近更新 更多