3
\$\begingroup\$

I have written the following code for searching and recursive directory.

Please review it.

Can it be optimized to avoid traversing symlink and handle "abort" signal inside for loop to continue the flow

void Dirs::scan_dir(string dir_name, DataBase &b, string owner) {
    fs::path p(dir_name);
    if (!fs::exists(p)) {
        std::cout<<"Path does not exist"<<std::endl;
        return;
    }
    if(fs::is_directory(p)) {
        fs::recursive_directory_iterator end_iter;
        std::vector<std::string> check_link;
        for(fs::recursive_directory_iterator begin(p); begin != end_iter; ++begin){
            try {
                fs::path tmp = begin->path().filename();
                string f_path = begin->path().relative_path().string();
                f_path = "/" + f_path;
                bool link_found = false;
                for(std::vector<std::string>::iterator it = check_link.begin();
                        it != check_link.end(); ++it) {
                    if (f_path.find(*it) != std::string::npos){
                        link_found = true;
                        std::cout<<"link name"<<*it<<" in path is  "<<f_path<<std::endl;
                        break;
                    }
                }
                if(link_found)
                    continue;
                if(fs::is_symlink(begin->path())) {
                    check_link.push_back(begin->path().filename());
                    continue;
                }

                if(fs::is_regular_file(begin->path())) {
                    std::vector<std::string> ls_file_output = this->getfiledetail(f_path);
                    string f_time = std::to_string(fs::last_write_time(begin->path()));
#if 1
                    b.insert_disk_analyze_query(ls_file_output[2], 
                                            this->local_time(), 
                                            tmp.string(),
                                            f_path,
                                            ls_file_output[3],
                                            f_time);
#endif
                }
            }
            catch(fs::filesystem_error &ex) {
                std::cout<<" File.."<<ex.what()<<std::endl;
                signal(SIGINT, signal_callback_handler);
            }
            catch(const std::exception &ex) {
                std::cout << ex.what() << std::endl;
            }
            catch(...) {
                std::cout<<"unkown error"<<std::endl;
            }
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.