user3009804
user3009804

Reputation: 349

Getting a directory root with C++

In order to develop a desktop application for Windows, which will need to know several user's directories of each user, I want to save for example the user's documents directory.

I have found out that already exists some macro (for example CSIDL_COMMON_DOCUMENTS) to know its directory's folder, but when I print this information I just get an integer and don't know how to get a string.

Any help will be welcomed.

Thanks a lot!

Upvotes: 0

Views: 3386

Answers (2)

user2637317
user2637317

Reputation:

You can use SHGetFolderPath():

#include <iostream>
#include <Windows.h>
#include <Shlobj.h>

int main()
{
    char path[MAX_PATH];
    if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL, 0, path)))
    {
        std::cout << path;
    }
}

Substitute CSIDL_COMMON_DOCUMENTS with any CSIDL you need, such as CSIDL_MYDOCUMENTS. To get another user's Documents folder, your app will have to impersonate that user, or otherwise obtain an access token for that user, before it can then query any CSIDL values that are specific to that user.

Upvotes: 4

Alan
Alan

Reputation: 46813

Using WinAPI, CSIDL_COMMON_DOCUMENTS is:

  1. Deprecated
  2. Not the right folder (it's common documents rather than the specific user document folder).

MSFT recommends using the KNOWNFOLDERID in lieu of CSIDL_COMMON_DOCUMENTS but it isn't supported prior to Windows Vista.

If you're building a Windows Application, consider using C++/CLI and .NET libraries, which makes "windowsy" things like accessing user folders, very straight forward.

using namespace System;
int main()
{
   Console::WriteLine();
   Console::WriteLine( "GetFolderPath: {0}", Environment::GetFolderPath( Environment::SpecialFolder::MyDocuments) );
}

MSDN Documentation on Environment::SpecialFolder

Upvotes: -1

Related Questions