分享

(原创)简单的目录遍历程序

 happy123god 2012-05-03
以下是我写的简单的目录遍历程序,支持递归遍历。



#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>


#define  MAX_PATH_NAME_LEN  4096

void easy_dir_traverse( char *dir_name)
{
    DIR * p_dir;
    struct dirent *p_dirent;
    struct stat  statbuf;
    char * p_full_path;
    unsigned int ui4_len = 0;

    if((p_dir = opendir(dir_name)) == NULL)
    {
        printf("fail to open %s \n",dir_name);
        printf(" please check if %s is a folder, or check"
               " if the path is correct \n",dir_name);
        return;
    }

    printf("\n %s traverse start : \n",dir_name);

    printf("files under %s are : \n",dir_name);
    
    while((p_dirent = readdir(p_dir)) != NULL)
    {
        if((strcmp(p_dirent->d_name,".") == 0) ||
           (strcmp(p_dirent->d_name,"..") == 0))
        {
            continue;
        }
        
        ui4_len = (strlen(p_dirent->d_name) + strlen(dir_name) + 2 );
        if(ui4_len <= MAX_PATH_NAME_LEN)
        {
            p_full_path = (char *)malloc(sizeof(char) * ui4_len);
            if(p_full_path == NULL)
            {
                printf(" fail to alloc memory for file full path \n");
                return;
            }
            else
            {
                sprintf(p_full_path,"%s/%s",
                        dir_name,p_dirent->d_name);
            }

            if(stat(p_full_path,&statbuf) < 0)
            {
                printf(" stat %s error \n",p_full_path);
                free(p_full_path);
                p_full_path = NULL;
                return ;
            }

            printf("%s\n",p_dirent->d_name);
            if(S_ISDIR(statbuf.st_mode))
            {
                easy_dir_traverse(p_full_path);
                printf("\n");
            }
            
            free(p_full_path);
            p_full_path = NULL;
                
        }
        else
        {
            printf(" path is too long , dir"
                   " traverse ends in this level \n");
        }
    }

    closedir(p_dir);
    printf("\n %s traverse end : \n",dir_name);
        
}

int main(int argc, char *argv[])
{
   
    if(argc != 2)
    {
        printf("invalid arguments : \n");
        printf("program_name  dir_to_traverse \n");
        return -1;
    }
    
    easy_dir_traverse(argv[1]);

    getchar();
    
    return 0;
}



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多