1

So what I want to do is make a username in a path be whatever user it is running under.

So for example, if the Windows user I was running this program under was named Bob, then I want to make the file on Bob's desktop. And not the one set to in the code.

I tried to explain it as well as possible, Thanks.

#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;
}

I am using Code::Blocks if that helps at all.

  • 4
    Possible duplicate of [Get current username in C++ on Windows](http://stackoverflow.com/questions/11587426/get-current-username-in-c-on-windows) – Deqing Jul 01 '16 at 00:21
  • This can't be done portably, so you should add some other tag(s) besides `C++`. If you mean for Windows alone, check out [SHGetKnownFolderPath](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx). – dxiv Jul 01 '16 at 00:37
  • I have a similar comment as @dxiv but I was going to suggest using [`SHGetSpecialFolderPath`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762204(v=vs.85).aspx) with [`CSIDL_DESKTOPDIRECTORY`](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762494(v=vs.85).aspx). – James Adkison Jul 01 '16 at 00:39

1 Answers1

0

Since you've mentioned a Windows user, I am assuming that you want a solution for Windows. Acquiring the username can be done using Win32 function SHGetKnownFolderPath. However, note that if you want your application to support Windows XP, then you will have to use an older (deprecated) function SHGetFolderPath. You can use this sample:

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);
}

And here is an example using 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

}

Note that the third parameter represents a token of the user for which trying to acquire desktop location. In a case when you app is started by elevating privileges from standard user account to an administrator account, the path returned by the functions mentioned above is the path to desktop of the administrator user. If you want to get the path to standard user, you will have to acquire token of that user and pass it as the third parameter.

Marko Popovic
  • 3,999
  • 3
  • 22
  • 37