我正在嘗試撰寫將檔案移動到垃圾箱的函式。例如,當我使用帶有 unicode 和空格的檔案路徑時,我無法將其發送到回收站。
...\Y?nü De?i?tir\Y?nü De?i?tir Sil.txt
我在論壇上找到了很多例子。但我無法正確運行它。
我哪里出錯了,你能幫我正確寫出函式嗎?
我的功能和代碼是這樣的:
. includes...
.
.
bool recycle_file_folder(std::string path) {
std::wstring widestr = std::wstring(path.begin(), path.end());
const wchar_t* widecstr = widestr.c_str();
SHFILEOPSTRUCT fileOp; //#include <Windows.h>;
fileOp.hwnd = NULL;
fileOp.wFunc = FO_DELETE;
fileOp.pFrom = widecstr; /// L"C:\\Users\\USER000\\Documents\\Y?nü De?i?tir\\Y?nü De?i?tir Sil.txt";
fileOp.pTo = NULL;
fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_NOCONFIRMATION | FOF_SILENT;
int result = SHFileOperation(&fileOp);
if (result != 0) {
return false;
}
else {
return true;
}
}
int main()
{
std::filesystem::path p("C:\\Users\\USER000\\Documents\\Y?nü De?i?tir\\Y?nü De?i?tir Sil.txt");
recycle_file_folder(p.string());
return 0;
}
現在,當您像這樣指定檔案時,它可以成功運行:
fileOp.pFrom = L"C:\\Users\\USER000\\Documents\\Y?nü De?i?tir\\Y?nü De?i?tir Sil.txt";
我如何調整它以適用于所有檔案?
uj5u.com熱心網友回復:
我認為您在 wstring 和 string 之間的轉換有問題。請注意,std::filesystem 支持轉換為 string 和 wstring,所以讓我們稍微重寫一下代碼
bool recycle_file_folder(std::wstring path) {
std::wstring widestr = path std::wstring(1, L'\0');
SHFILEOPSTRUCT fileOp;
fileOp.hwnd = NULL;
fileOp.wFunc = FO_DELETE;
fileOp.pFrom = widestr.c_str();
fileOp.pTo = NULL;
fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_NOCONFIRMATION | FOF_SILENT;
int result = SHFileOperation(&fileOp);
if (result != 0) {
return false;
}
else {
return true;
}
}
int main()
{
std::filesystem::path p("C:\\Users\\USER000\\Documents\\Y?nü De?i?tir\\Y?nü De?i?tir Sil.txt");
recycle_file_folder(p.wstring());
return 0;
}
uj5u.com熱心網友回復:
帶有 unicode 和空格的檔案路徑
問題不在于空格,而在于非 ASCII 字符。
std::wstring widestr = std::wstring(path.begin(), path.end());
這不是將某些代碼頁的字符轉換為 UTF-16 的正確方法。您必須使用此問答中建議的方法:C Convert string (or char*) to wstring (or wchar_t*)(忽略 Pietro M 的答案,查看其他答案)
或者,使用SHFileOperationA, 和SHFILEOPSTRUCTA,但這是一個更糟糕的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/376682.html
下一篇:突出顯示時XP彈出選單圖示不透明
