Linux中目录扫描程序的实现:
(1)C语言实现。重点要用到中的库函数opendir,readdir,closedir,中的系统调用chdir。下面为实现文件,文件名为printdir.c。
#include
#include
#include
#include
#include
#include
/* 目录扫描,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);
pr