下面是一个子目录的扫描程序,得到一个自目录清单,子目录中的每个文件单独列在一行上:
#include
#include
#include
#include
#include
#include
void printdir(char *dir )
{
DIR *dp;
struct dirent *entry; // in
struct stat statbuf;
if ((dp=opendir(dir))==NULL) {
fprintf(stderr,"Cannot open directory:%s\n",dir);
return;
}
chdir(dir);//将进程的工作目录交给dir
while ((entry = readdir(dp))!=NULL) {
/*readdir(dp)读取下一个目录项,返回包含文件信息的结构指针entry*/
lstat(entry->d_name,&statbuf);//读取文件的属性,将其放到statbuf中
if (S_ISDIR(statbuf.st_mode)) { //判断是否为目录
/*found directory but ignore .and ..*/
if (strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)
continue;
printf("\n\n");
printf("Directory: => %s/\n",entry->d_name);
/*rescurse at a new indent level*/
printf("File:\n");
printdir(entry->d_name);
}
else printf("->%s\n",entry->d_name);
}
chdir("..");
closedir(dp);//关闭dp所指向的目录
}
int main()
{
printdir("/home/caojiangfeng/Code/Java");
return 0;
}
caojiangfeng@caojiangfeng-laptop:~$ gcc -o print_dir print_dir.c
caojiangfeng@caojiangfeng-laptop:~$ ./print_dir
->Hello.class
->father.java
->A.class
->HTTPClient.java
->HTTPClient.class
Directory: => javaMail/
File:
->Test.java
->Email_Autherticator.java
->Mail.java~
->Mail.java
...
阅读(1411) | 评论(0) | 转发(0) |