[英]How can i create a dir in Documents folder? [C++]
我試圖在 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");
如您所見,我正在嘗試在文檔文件夾中創建一個名為“新建”的新文件夾。 文檔的路徑正確,但未創建目錄。
這是使用_bstr_t
來避免使用Unicode,新路徑被轉換為ANSI,除非原始路徑是ANSI,否則將無效,(或ASCII要保證)
只需填充L"\\New"
和寬字符串函數即可解決問題。
您還必須按照文檔中的說明釋放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());
std::filesystem::path class 理解 Unicode 就好了,所以你不需要弄亂那里的任何助手。 此外,您需要檢查兩個function 結果以確定成功或失敗:
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 文件夾和創建目錄的功能分成兩個單獨的功能,但上面的就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.