文件搜索从 C:\$Recycle.Bin\S-1-5-18 开始并导致 filesystem_error

问题描述 投票:0回答:1

我正在编写一个程序,从 C:\ 开始按名称搜索 Windows 目录中的文件。我使用 recursive_directory_iterator 和来自 std::filesystem 的路径。 问题是,虽然用户输入被正确读取并且核心逻辑看起来很好,但程序直接开始搜索,如下所示: C:\ -> C:\$Recycle.Bin -> C:\$Recycle.Bin\S-1 -5-18 然后粉碎。

我的代码:

std::filesystem::path System::find_file_path(const std::string& file_name,
                                             std::filesystem::path file_path)
{
    // iterating recursively so all directories will be searched through
    for (const auto& entry : std::filesystem::recursive_directory_iterator(file_path))
        if (entry.is_directory())
        {
            // changing C:\\ to directory's path and searching again
            auto new_path = entry.path();
            auto found_path = find_file_path(file_name, new_path);
        }
        else {    // we found a file
                 //checking if it is the one we search for
            if (entry.path().filename() == file_name) {
                return entry.path();
            }
        }
    return starting_point;    // the file does not exist, return C:\\
}

// ...

// main
std::string System::path = "C:\\";
int main()
{
    std::string input_file{};
    std::cout << "hello! enter file name here: ";
    std::cin >> input_file;
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::filesystem::path path = System::find_file_path(input_file, System::path);
    std::cout << path;
}

我尝试过使用迭代器、路径、字符串等一切,但代码在 std::filesystem::filesystem_error、system_error 或堆栈溢出中崩溃。

我需要知道为什么我的代码直接进入 C:\$Recycle.Bin 以及如何防止这种情况发生。或者,如果有其他错误我看不到,因为我是 C++ 的初学者,我们将非常感谢您的帮助。

提前谢谢您。

c++ c++17 filesystems file-search std-system-error
1个回答
0
投票

添加异常处理并删除冗余递归我相信您正在寻找的代码类似于(完全未经测试)...

std::filesystem::path System::find_file_path(const std::string& file_name,
                                             std::filesystem::path file_path)
{
    for (const auto& entry : std::filesystem::recursive_directory_iterator(file_path)) {
        try {

            /*
             * Checking to see if it's the one we're searching for.
             */
            if (entry.path().filename() == file_name) {
                return entry.path();
            }
        }
        catch (std::exception &ex) {

            /*
             * Handle exception...
             */
        }
    }
    return starting_point;
}
© www.soinside.com 2019 - 2024. All rights reserved.