Linux文件遍历

该程序不知为何会在readdir中出现段错误,当遍历到较深的目录或者目录较长时会出现段错误,该程序是在虚拟机上跑的不知道是不是因为是虚拟机的事,以为之前在物理机上跑时没有遇见过。


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

//多层目录遍历,此处的目录路径最好为绝对路径
int ls_search_file(char *path)
{
    char tmp[64] = {0};
    DIR *dir;
    struct dirent *dt;
    struct stat sta;

    dir = opendir(path);
    if (dir == NULL)
        return -1; 
perror("opendir");
    while((dt = readdir(dir)) != NULL) {                                                                                                                                                                       
        if (strcmp(dt->d_name, ".") == 0 || strcmp(dt->d_name, "..") == 0)
           continue;
        puts(dt->d_name);
        sprintf(tmp, "%s/%s", path, dt->d_name); //设置为绝对路径,非绝对路径时,lstat文件获取文件属性时失败,导致S_ISDIR计算错误
        lstat(tmp, &sta); //注意此处最后不要用dt->d_type判断文件类型,部分文件系统不支持,详细参考man手册
        if (S_ISDIR(sta.st_mode)) {//S_ISDIR提取文件属性是否是一个目录,即7种文件类型C D - S P B L
           ls_search_file(tmp);
       }   
    }   

    closedir(dir);
    return 0;
}

//指定目录层遍历,只能遍历一层,无法递归遍历,测试使用telldir和seekdir进行遍历位置定位
int l1_search_file(char *path)
{
    DIR *dir;
    struct dirent *dt;
    struct stat sta;
    long offset;
    int i = 0;

    dir = opendir(path);
    if (dir == NULL)
        return -1; 

    while((dt = readdir(dir)) != NULL) {
        if (strcmp(dt->d_name, ".") == 0 || strcmp(dt->d_name, "..") == 0)
           continue;
        puts(dt->d_name);

        if (i++ == 2)
           offset = telldir(dir); //得到当前打开的目录位置
    }   

    seekdir(dir, offset); //修改目录位置,并以新的位置遍历显示目录
    //注意:seekdir和readdir不要用在用一个while中,会使seekdir失去作用,通过seekdir修改的dir会被readdir重新修改回去

    while((dt = readdir(dir)) != NULL) {
        if (strcmp(dt->d_name, ".") == 0 || strcmp(dt->d_name, "..") == 0)
           continue;
        puts(dt->d_name);
    }  

    closedir(dir);
    return 0;
}

int main(int argc, char *argv[])
{
    //ls_search_file("/root");
    ls_search_file("/root/.vim/bundle/taglist.vim/.git/objects/pack");
    printf("-------------------------\n");
    //l1_search_file("/root/aa");

    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值