Linux中目录扫描程序的实现:
(1)C语言实现。重点要用到<dirent.h>中的库函数opendir,readdir,closedir,<unistd.h>中的系统调用chdir。下面为实现文件,文件名为printdir.c。

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

/* 目录扫描,dir为目录名,depth为初始的缩进空格数 */
void printdir(char *dir,int depth){    
	DIR *dp;    
	struct dirent *entry;    
	struct stat statbuf;    
	if((dp=opendir(dir))==NULL){ /* 打开目录,返回DIR结构dp */        
		fprintf(stderr,"cannot open directory: %s/n",dir);        
		return;    
	}    
	chdir(dir);    
	while((entry=readdir(dp))!=NULL){ /* 读取目录项(目录中的文件或子目录) */        
		lstat(entry->d_name,&statbuf); /* 获取文件状态信息,放在statbuf结构中 */        
		if(S_ISDIR(statbuf.st_mode)){           
			/* 忽略目录.和目录.. */            
			if(strcmp(".",entry->d_name)==0 || strcmp("..",entry->d_name)==0)
				continue;           
			/* 输出的目录名后加一斜杠,缩进的空格数由depth指定 */            
			printf("%*s%s/\n",depth,"",entry->d_name);             
			printdir(entry->d_name,depth+4); /* 递归调用以遍历子目录 */       
		} else printf("%*s%s\n",depth,"",entry->d_name);
	}    
	chdir(".."); /* 切换到上层目录 */   
	closedir(dp);
}
		
int main(int argc,char* argv[]){    
	char *topdir=".";    
	if(argc>=2)        
		topdir=argv[1];    
	printf("Directory scan of %s:/n",topdir);    
	printdir(topdir,0);   
	exit(0);
}


 (2)Shell编程实现。写一个递归函数recdir来显示指定目录下所有文件名(要用到递归调用)。recls函数根据传进来命令行参数还可以一次扫描多个目录。下面为实现文件,文件名为lsrec。

# 递归显示目录内容
recls()
{
  singletab="\t" # 缩进为1个tab符,即8个空格
  for tryfile in "$@"; do
      if [ -f "$tryfile" ]; then
          echo "$tryfile" # 显示传进来的文件
      elif [ -d "$tryfile" ]; then # 若是一个目录
         echo "$tryfile/" # 显示传进来的目录
         thisfile=$tryfile
         # 显示目录下的所有文件名,并把它们作为参数来调用recdir
         recdir $(command ls $tryfile)
      fi
  done
  unset dir singletab tab
}
# 显示指定目录下的所有文件名
recdir()
{
  tab=$tab$singletab # 增加一个缩进的tab
  for file in "$@"; do # 对目录下的每一个文件名
     thisfile=$thisfile/$file # thisfile变成当前file的完整名
     if [ -f "$thisfile" ]; then
        echo -e "$tab$file"
     elif [ -d $thisfile ]; then
        echo -e "$tab$file/"
        recdir $(command ls $thisfile) # 递归调用以显示子目录
     fi
     thisfile=${thisfile%/*} # 当前file处理完后,截掉它
   done
   tab=${tab%"\t"} # 截掉一个缩进符,返回上一层
}
if [ -z "$1" ]; then
    recls .
else
    recls $@ # 参数由命令行传入
fi

Logo

更多推荐