【问题标题】:How can i create a dir in Documents folder? [C++]如何在 Documents 文件夹中创建目录? [C++]
【发布时间】:2021-11-17 11:00:53
【问题描述】:

我正在尝试在 Documents 文件夹中创建一个目录或子目录。

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

如您所见,我正在尝试在 Documents 文件夹中创建一个名为“New”的新文件夹。 文档路径正确,但未创建目录。

【问题讨论】:

  • 题外话了,但是...为什么要经历所有这些而不是简单地使用std::filesystem::create_directory
  • 首先你的代码有一些代码味道。就像你只设置myPath 如果SUCCEEDED(hr) 返回true。但函数的其余部分以任何一种方式执行。所以也许SHGetKnownFolderPath 没有成功,因此其余代码在一个空字符串上操作。
  • 我会更改的,谢谢,文档路径已显示,我尝试在调试模式下显示它
  • 另一件可能不太理想的事情是使用两个不同的字符串类std::wstring_bstr_t。您可能只需要一个并且可以删除另一个。
  • 我也用谷歌搜索了_mkdir_mkdir 的参数不是_bstr_t 而是const char *。但你最初有一个const wchar_t *,因此你可能应该使用_wmkdir。同时放弃_bstr_t,只使用wstring。写str += L"\\New";,后跟int status = _wmkdir(str.c_str());

标签: c++


【解决方案1】:

这是使用_bstr_t来避免使用Unicode,新路径被转换为ANSI,除非原始路径是ANSI,否则将无效,(或保证ASCII)

只需填充L"\\New" 和宽字符串函数即可解决问题。

您还必须按照documentation 中的说明释放ppszPath

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

【讨论】:

    【解决方案2】:

    std::filesystem::path 类可以很好地理解 Unicode,因此您无需在其中弄乱任何帮助程序。此外,您需要检查 both 函数结果以确定成功或失败:

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

    运算结果在变量success中表示。

    我个人会把获取用户的Documents文件夹和创建目录的功能分离成两个独立的功能,但是上面的就可以了。

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2021-01-18
      • 2011-05-05
      相关资源
      最近更新 更多