linux用C如何判断一个目录是否为空

3352阅读 0评论2008-05-25 sdccf
分类:C/C++

作者: opius     出自:
用opendir打开一个目录,得到结构DIR*,但是没有关于其下有多少文件、子目录的数据,我用比较土的办法,遍历目录readdir,计算其下有多少文件和子目录,当然也不是连子目录下的东西也找。

下面的程序在solaris8、gcc编译通过的,如果一个目录是空的,输出为2。
#include
#include
#include
int main(int argc , char **argv)
{
DIR *dirp;
int num=0;

dirp = opendir(argv[1]);
while (dirp) {
if ( readdir(dirp) != NULL)
++num;
else
break;
}

closedir(dirp);
printf("%d\n",num);
}

shell中判断目录为空
#!/bin/ksh
# Check if a directory is empty or not

if [ $# = 0 ]
then
echo
echo "use this tool to check if directory is empty"
echo "for example: isEmpty dirName "
echo
exit 1
fi

case $(( 0 + $(find $1 2>&- |head -2|wc -l))) in

0) echo Permission denied ! ;;
1) echo Directory is empty ! ;;
*) echo Directory is not empty ! ;;

esac

上一篇:Keepalived + Nginx 类型服务下高可靠Linux系统设计
下一篇:彻底告别Linux下没有C/C++好用IDE的时代