I am trying to write function to move files to trash. For example when I use a file path with unicode and whitespace I cannot send it to the Recycle Bin.
...\Yönü Değiştir\Yönü Değiştir Sil.txt
I found many examples on the forum. But I couldn't run it correctly.
Where did I go wrong, Can you help me write the function correctly?
My function and code is like this:
. 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;
}
Now it works successfully when you specify the file like this:
fileOp.pFrom = L"C:\\Users\\USER000\\Documents\\Yönü Değiştir\\Yönü Değiştir Sil.txt";
How do I adapt this to function for all files?
CodePudding user response:
I think your conversion between wstring and string has problem. Note that std::filesystem supports converting to both string and wstring so let's re-write your code a bit
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;
}
CodePudding user response:
a file path with unicode and whitespace
The problem is not in whitespace, it is with non-ASCII characters.
std::wstring widestr = std::wstring(path.begin(), path.end());
This is not a correct way to convert characters of some code page to UTF-16. You'll have to use a method suggested in this Q&A: C Convert string (or char*) to wstring (or wchar_t*) (Ignore the answer by Pietro M, look into other answers)
Alternately, use SHFileOperationA
, and SHFILEOPSTRUCTA
, but it is a worse solution.
CodePudding user response:
I understood the logic with the answers you gave and fixed my problem. Thank you very much for your answers.