linux用C如何鉴别一个目录能否为空



作者: opius     出自: http://www.linuxdiyf.com
用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






版权声明: 原创作品,许诺转载,转载时请务必以超链接编制标明文章 原始出处 、作者信息和本声明。不然将追究法律责任。

posted @ 2011-03-07 18:33  蓝色的天空III  阅读(283)  评论(0编辑  收藏  举报