+ -
当前位置:首页 → 问答吧 → 内核无关,C语言遍历目录的问题,很奇怪。

内核无关,C语言遍历目录的问题,很奇怪。

时间:2010-08-09

来源:互联网

#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <libgen.h>
#include <dirent.h>



void get_dir(char *dir)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    if((dp = opendir(dir)) == NULL)
    {
        //fprintf(stderr,"cannot open directory: %s\n", dir);
       
        return;
    }
    while((entry = readdir(dp)) != NULL)
    {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode))
        {
            //printf("%s \n",entry->d_name);  这个是打出文件或文件名
            
            if(strcmp(".",entry->d_name) == 0 ||
                strcmp("..",entry->d_name) == 0)
            {
                continue;
            }
            char tmp[4100];
            strcpy(tmp,dir);
            strcat(tmp,entry->d_name);
            strcat(tmp,"/");
            get_dir(tmp);
        }
        else
        {
           //printf("%s \n",entry->d_name); 这个是打出文件或文件名
        }
       
    }
    closedir(dp);
   
}




int main(int argc,char *argv[])
{
    get_dir(argv[1]);
   
   
    return 0;
}

代码就是这样,递归遍历,if(S_ISDIR(statbuf.st_mode))判断拿到的statbuf是目录还是文件,然后就是那两个printf,如果是目录,就打出第一个printf,显示目录名,如果不是目录,那就是else里面的printf,输出文件名。
但问题是,printf之后发现,这两个printf输出的都属于有的是目录,有的是文件,if(S_ISDIR(statbuf.st_mode))似乎不起作用的样子?

作者: zonelight   发布时间: 2010-08-09

aaa

作者: xiaoQ008   发布时间: 2010-08-09

ORZ................CU还有乱水的人。。。。。。。。。。。。。

作者: zonelight   发布时间: 2010-08-09

热门下载

更多