如何在documents文件夹内创建目录?

时间:2018-10-28 01:16:47

标签: c++ windows winapi

这是我尝试查找任何用户中的文档文件夹,然后创建文件夹的尝试。我是C ++的新手,只是想弄清楚目录是如何工作的

  void useraccess::createtxt() {
    //name is a pre-defined string
    cout << "Creating user\n";

    #ifdef _WIN32
    LPTSTR path = NULL;
    HRESULT hr = SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &path);

    if (SUCCEEDED(hr)) {
        path + \\name;
        CreateDirectoryA(path, NULL);
    }
    else {
        cout << "Error finding documents folder";
    }

    #elif __APPLE__

    #else
        cout << "Error";
    #endif
}

1 个答案:

答案 0 :(得分:1)

#include <cstdlib>
#include <string>
#include <iostream>

#include <windows.h>
#include <shlobj_core.h>


int main()
{
    PWSTR path_temp;

    if (SHGetKnownFolderPath(FOLDERID_PublicDocuments, 0, nullptr, &path_temp) != S_OK) {
        std::cerr << "SHGetKnownFolderPath() failed :(\n\n";
        return EXIT_FAILURE;
    }

    std::wstring path{ path_temp };
    CoTaskMemFree(path_temp);

    path += L"\\foobar";

    if (SHCreateDirectory(nullptr, path.c_str()) != ERROR_SUCCESS) {
        std::cerr << "SHCreateDirectory() failed :(\n\n";
        return EXIT_FAILURE;
    }

    std::wcout << L"Directory \"" << path << L"\" created.\n\n";
}