C++ learning "How to use code to operate files in the recycle bin"

Method 1: Set different SHFILEOPSTRUCT structures, and call the SHFileOperation function to implement file operations such as copying, deleting, and moving

SHGetSpecialFolderLocation function:

原型:HRESULT SHGetSpecialFolderLocation(HWND hwnd, int csidl,
PIDLIST_ABSOLUTE* ppidl)

This function is used to get the physical path of a special folder. It accepts the following parameters:

hwnd: optional parameter, specifies the handle of the parent window. Can be set to NULL if no window association is required.
csidl: Indicates the identifier of the special folder (CSIDL), which is used to specify the folder to be obtained.
ppidl: A pointer to PIDLIST_ABSOLUTE type, used to receive the ITEMIDLIST of the folder.
Function: According to the given special folder identifier, this function will return the physical path of the corresponding folder. By using this function to obtain the physical path of the recycle bin folder, the files in it can be further manipulated.

SHGetPathFromIDList function:

原型:BOOL SHGetPathFromIDList(PCIDLIST_ABSOLUTE pidl, LPWSTR pszPath)

This function is used to return the path of the folder according to ITEMIDLIST (in this case, PIDLIST_ABSOLUTE obtained through SHGetSpecialFolderLocation).

Function: This function converts ITEMIDLIST into a string path of a folder.

SHFileOperation function:

Prototype: int SHFileOperation(const SHFILEOPSTRUCT* lpFileOp)

This function is used to perform file operations such as copy, move, and delete. It accepts the following parameters:

lpFileOp: A pointer to a SHFILEOPSTRUCT structure describing the file operation to be performed.
Function: This function performs file operations, and can copy, move or delete files to the specified location, including the recycle bin. The FOF_ALLOWUNDO flag can be set to enable undo functionality.

SHFILEOPSTRUCT structure:

定义:typedef struct _SHFILEOPSTRUCT
{
HWND hwnd;
UINT wFunc;
LPCWSTR pFrom;
LPCWSTR pTo;
FILEOP_FLAGS fFlags;
BOOL fAnyOperationsAborted;
LPVOID hNameMappings;
LPCWSTR lpszProgressTitle;
} SHFILEOPSTRUCT, *LPSHFILEOPSTRUCT;

Member variables:

hwnd: An optional parameter, indicating the handle of the parent window. wFunc: Indicates the type of file operation to be performed, such as copy, move, delete, etc.
pFrom: Path string pointing to source file/folder. pTo: Point to the target file/folder path string.
fFlags: Flag bits controlling file operations, such as FOF_ALLOWUNDO, FOF_NOCONFIRMATION, etc.
fAnyOperationsAborted: TRUE if any operation was canceled by the user.
hNameMappings: reserved parameter, should be set to NULL. lpszProgressTitle: Optional parameter to display a custom title in the progress dialog.

This structure describes the details of the file operation to be performed, including source file/folder path, target path, operation type and flags, etc. Pass this structure to the SHFileOperation function to perform corresponding file operations.

Code example:

Using the Shell API: You can use the Windows Shell API to access the Recycle Bin and get information about the recovered files.

1. Use the SHGetSpecialFolderLocation function to obtain the physical path of the recycle bin by specifying the CSIDL_BITBUCKET identifier of the recycle bin.
2. Use the SHGetPathFromIDList function to convert the recycle bin path into a string format and store it in sFolderPath.
3. Build a search path sSearchPath for traversing files in the recycle bin folder.
4. Use FindFirstFile and FindNextFile functions to traverse each file in the Recycle Bin folder.
5. For each file, use the _tprintf function to output its filename and full path on the console.
6. Finally, use FindClose to close the file search handle.


#include <Windows.h>
#include <ShlObj.h>

int main() {
    
    
    // 获取回收站的路径
    LPITEMIDLIST pidlBin;
    SHGetSpecialFolderLocation(NULL, CSIDL_BITBUCKET, &pidlBin);
    
    // 将回收站的路径转换为字符串格式
    TCHAR szFolderPath[MAX_PATH];
    SHGetPathFromIDList(pidlBin, szFolderPath);
    
    // 构建搜索路径
    TCHAR szSearchPath[MAX_PATH];
    _stprintf_s(szSearchPath, MAX_PATH, _T("%s\\*"), szFolderPath);
    
    // 遍历回收站文件夹中的文件
    WIN32_FIND_DATA findData;
    HANDLE hFind = FindFirstFile(szSearchPath, &findData);
    if (hFind != INVALID_HANDLE_VALUE) {
    
    
        do {
    
    
            // 输出文件名和完整路径
            _tprintf(_T("File: %s\n"), findData.cFileName);
            _tprintf(_T("Path: %s\\%s\n"), szFolderPath, findData.cFileName);
        } while (FindNextFile(hFind, &findData));
        
        FindClose(hFind);
    }
   
    return 0;
}

Use the SHFILEOPSTRUCT structure and SHFileOperation function of the Shell API to perform file operations, including restoring files to their original paths.

#include <Windows.h>
#include <ShlObj.h>

int main() {
    
    
    // 设置恢复操作的源文件路径和目标文件夹路径
    TCHAR szSourceFilePath[] = _T("C:\\RecycleBin\\file.txt");
    TCHAR szDestinationFolderPath[] = _T("C:\\OriginalPath");
    
    // 构建SHFILEOPSTRUCT结构
    SHFILEOPSTRUCT fileOpStruct;
    ZeroMemory(&fileOpStruct, sizeof(SHFILEOPSTRUCT));
    fileOpStruct.wFunc =_RENAME;
    fileOpStruct.pFrom = szSourceFilePath;
    fileOpStruct.pTo = szDestinationFolderPath;
    fileOpStruct.fFlags = FOF_ALLOWUNDO;
    
    // 执行恢复操作
    int result = SHFileOperation(&fileOpStruct);
    if (result == 0) {
    
    
        // 恢复成功
        // ...
    }
    
    return 0;
}

Delete files in the recycle bin:

#include <Windows.h>
#include <Shlobj.h>
#include <iostream>

int main() {
    
    
    LPITEMIDLIST pidlBin;
    SHGetSpecialFolderLocation(NULL, CSIDL_BITBUCKET, &pidlBin);
    
    // 构建文件操作的结构体
    SHFILEOPSTRUCT fileOpStruct;
    ZeroMemory(&fileOpStruct, sizeof(SHFILEOPSTRUCT));
    fileOpStruct.hwnd = NULL;  // 父窗口句柄(可选)
    fileOpStruct.wFunc = FO_DELETE;  // 执行删除OpStruct.pFrom = reinterpret_cast<LPCWSTR>(pidlBin);  // 源文件路径
    fileOpStruct.fFlags = FOF_ALLOWUNDO | FOF_NO_UI;  // 标志位
    
    int result = SHFileOperation(&fileOpStruct);  // 执行文件操作
    if (result == 0 && !fileOpStruct.fAnyOperationsAborted) {
    
    
        std::cout << "文件删除成功!" << std::endl;
    } else {
    
    
        std::cerr << "文件删除失败:" << result << std::endl;
    }
    
    CoTaskMemFree(pidlBin);  // 释放内存
    
   ;
}

Method 2: Use a third-party library, such as Boost and Qt, which provides a more advanced file system operation interface.

Take the Boost library as an example:

Boost is an open source collection of C++ libraries that enhance functionality and performance. It provides many high-quality, portable and extensively tested modules and components, covering everything from basic data structures to advanced functions. The following is a brief introduction to some commonly used modules and their functions in the Boost library:

1. Boost.Filesystem (file system): This module provides a convenient and cross-platform interface for C++ to operate the file system, including file path operation, directory traversal, file access, etc.

boost::filesystem::path: Indicates the path of a file or directory, and provides a wealth of path operation functions, such as obtaining the parent path, splicing paths, and judging whether the path exists.
boost::filesystem::directory_iterator: Iterator, used to traverse the files and subdirectories under the specified directory.
boost::filesystem::remove(): Delete the file or directory at the specified path.
boost::filesystem::copy(): Copies a file or an entire directory to a specified location.

2. Boost.Regex (regular expression): This module provides support for regular expressions, allowing pattern matching and searching in text through regular expressions.

boost::regex: Represents a regular expression object. boost::regex_match(): Use the specified regular expression to fully match the string.
boost::regex_search(): Searches for a substring that satisfies a regular expression in a string.

3. Boost.DateTime (date and time): This module provides processing functions for date, time and time intervals, including date and time representation, calculation, formatting, etc.

boost::posix_time::ptime: Represents a time point accurate to milliseconds. boost::gregorian::date: Represents a date.
boost::date_time::duration: Indicates a time interval.
boost::posix_time::time_duration: Indicates the length of time.
boost::date_time::period_formatter: Class for formatting dates and times.

In addition to the above modules, the Boost library provides many other modules, including but not limited to multithreading, smart pointers, math libraries, network programming, serialization, and more. These modules provide C++ developers with a wealth of tools and features to facilitate the development of efficient and reliable applications.

Get recycle bin file information:

#include <boost/filesystem.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main() {
    
    
    // 获取回收站的路径
    fs::path recycleBinPath = fs::path(fs::current_path()) / ".Trash";
    
    // 遍历回收站文件夹中的文件
    for (const auto& entry : fs::directory_iterator(recycleBinPath)) {
    
    
        // 输出文件名以及路径
        std::cout << "File: " << entry.path().stem().string() << std::endl;
        std::cout << "Path: " << entry.path().string() << std::endl;
    }
   
    return 0;
}

Use the boost::filesystem::rename function of the Boost library to restore the file to its original path:

#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main() {
    
    
    // 设置恢复操作的源文件路径和目标文件夹路径
    fs::path sourceFilePath = "C:\\RecycleBin\\file.txt";
    fs::path destinationFolderPath = "C:\\OriginalPath";
    // 执行恢复操作
    fs::rename(sourceFilePath, destinationFolderPath / sourceFilePath.filename());
    
    return 0;
}

For more development and application case studies of the boost library, you can refer to "Exploring the Boost Library: In-depth Analysis of the C++ Quasi-Standard Library" written by Mr. Luo Jianfeng. It seems that there are two related books, both of which are written by him. Friends can, learn more.

Guess you like

Origin blog.csdn.net/u014740628/article/details/131362399