内核无关,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))似乎不起作用的样子?
#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
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28