遍历目录文件——Windows文件目录和Unix文件目录

1.遍历Unix目录code

int traverse(const char *current_path)
{
    struct stat st;
    int ret = stat(current_path, &st);
    if (ret != 0)
    {
        return -1;
    }
    
    char path[512] = {0};
    if (S_ISDIR(st.st_mode))
    {
        DIR *dir = opendir(current_path);
        if (NULL == dir)
        {
            return -1;
        }
        
        struct dirent *ptr = NULL;
        while((ptr = readdir(dir)) != NULL)
        {
            if(strstr(ptr->d_name, ".") == ptr->d_name)
            {
                continue;
            }
            
            snprintf(path, sizeof(path), "%s/%s", current_path, ptr->d_name);
            traverse(path);
        }
        
        closedir(dir);
    }
    else
    {
        printf("%s\n", path);
    }
    
    return 0;
}

非递归实现递归

int traverse(const char *path)
{
    struct dirent *entry = NULL;
    DIR *dir = NULL;
    
    std::stack<std::string> ss;
    ss.push(path);
    while(!ss.empty())
    {
        std::string child = ss.top();
        ss.pop();
        dir = opendir(child.c_str());
        if (NULL == dir)
        {
            printf("@error:%s, %d, %s\n", child.c_str(), ss.size(), strerror(errno));
            return -1;
        }
        
        for(int i = 0; i < 10000 && ((entry = readdir(dir)) != NULL); i++)
        {
            if (strstr(entry->d_name, ".") ==  entry->d_name)
            {
                continue;
            }
            
            if (strstr(entry->d_name, "Application Support"))
            {
                continue;
            }
            
            if (entry->d_type == DT_DIR)
            {
                char str[1024] = {0};
                snprintf(str, sizeof(str), "%s/%s", child.c_str(), entry->d_name);
                ss.push(str);
            }
            else
            {
                printf("file:%s\n", entry->d_name);
            }
        }
        closedir(dir);
        
    }
    return 0;
}

2.遍历Windows目录string

int traverse(TCHAR *szDir)
{
    TCHAR path[MAX_PATH] = { 0 };
    WIN32_FIND_DATA ffd = {0};
    HANDLE hFind = INVALID_HANDLE_VALUE;
    
    hFind = FindFirstFile(szDir, &ffd);
    while (FindNextFile(hFind, &ffd) != 0)
    {
        
        sprintf_s(curPath, "%s\\%s", dir, ffd.cFileName);
        
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0)
            {
                continue;
            }

            int ret = traverse(path);
            if (ret != 0 )
            {
                FindClose(hFind);
                return -1;
            }
        }
        else
        {
           //文件
        }
    }
    
    FindClose(hFind);
    
    return 0;
}