recursive file search

前端 未结 6 901
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 13:49

I\'m trying to figure out how to work this thing out .. For some reason, it ends at a certain point.. I\'m not very good at recursion and I\'m sure the problem lies somewher

6条回答
  •  时光说笑
    2021-01-06 14:26

    Recursive file search with dirent.h

    #include 
    #include 
    #include     
    
    bool isUpDirecory(const char* directory) {
            if (strcmp(directory, "..") == 0 || strcmp(directory, ".") == 0)
                return true;
            else
                return false;
        }
    
        bool findFile(const std::string& fileName, const std::string& path,
                std::string& resultPath) {
            dirent* entry;
            DIR* dir = opendir(path.c_str());
    
            if (dir == NULL)
                return false;
    
            while ((entry = readdir(dir)) != NULL) {
                if (entry->d_type == DT_REG) {
                    if (fileName.compare(entry->d_name) == 0) {
                        resultPath = path + "/" + entry->d_name;
                        closedir(dir);
                        return true;
                    }
                }
            }
    
            rewinddir(dir);
    
            while ((entry = readdir(dir)) != NULL) {
                if (entry->d_type == DT_DIR) {
                    if (!isUpDirecory(entry->d_name)) {
                        std::string nextDirectoryPath = path + "/" + entry->d_name;
                        bool result = findFile(fileName, nextDirectoryPath, resultPath);
                        if (result == true) {
                            closedir(dir);
                            return true;
                        }
                    }
                }
            }
    
            closedir(dir);
            return false;
        }
    
        int main() {
            std::string path;
            bool result = findFile("text.txt", "/home/lamerman/", path);
            std::cout << path << std::endl;
            return 0;
        }
    

提交回复
热议问题