Home > other >  How can i create a dir in Documents folder? [C ]
How can i create a dir in Documents folder? [C ]

Time:11-18

Im trying to create a directory , or a subdirectory in the Documents folder.

 PWSTR   ppszPath;    // variable to receive the path memory block pointer.

    HRESULT hr = SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &ppszPath);

    std::wstring myPath;
    if (SUCCEEDED(hr)) {
        myPath = ppszPath;      // make a local copy of the path
    }

const wchar_t* str = myPath.c_str();
    _bstr_t b(str);
   
    int status = _mkdir(b "\\New");

As you can see , I'm trying to create a new folder named "New" in Documents Folder. The path to the documents is correct but the dir is not created.

CodePudding user response:

This is using _bstr_t to avoid using Unicode, the new path is converted to ANSI and will be invalid unless the original path was ANSI, (or ASCII to be guaranteed)

Just pad L"\\New" and wide string functions to solve the problem.

You also have to free ppszPath as stated in documentation

std::wstring myPath;
wchar_t *ppszPath;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &ppszPath);
if (SUCCEEDED(hr)) 
{
    myPath = ppszPath;
    CoTaskMemFree(ppszPath);
}//error checking?

myPath  = L"\\New";
std::filesystem::create_directory(myPath)
//or _wmkdir(myPath.c_str());

CodePudding user response:

The std::filesystem::path class understands Unicode just fine, so you don’t need to mess with any helpers there. Also, you need to check both function results to determine success or failure:

bool success = false;
PWSTR documents_path = nullptr;
if (SUCCEEDED( SHGetKnownFolderPath( FOLDERID_Documents, 0, NULL, &documents_path ) ))
{
  using namespace std::filesystem;
  success = create_directory( path{ documents_path } / "new_folder" );
  CoTaskMemFree( documents_path );
  documents_path = nullptr;
}

The result of the operation is indicated in the variable success.

I would personally separate the functions of obtaining the user’s Documents folder and the directory creation into two separate functions, but the above will do just fine.

  •  Tags:  
  • c
  • Related