扫描/tmp目录下的文件和子目录:
#include
#include
#include
#include
#include
#include
// int mkdir(const char *path,mode_t mode);
void printdir(char *dir,int depth)
{
DIR *dp;
//int closedir(DIR *dirp);
struct dirent *entry;
// struct dirent {
// long d_ino;
// __kernel_off_t d_off;
// unsigned short d_reclen;
// char d_name[256]; /* We must not include limits.h! */
// };
struct stat statbuf;
//int lstat(const char *path,struct stat *buf);
if((dp = opendir(dir)) == NULL)
{
fprintf(stderr,"cannot open directory: %s\n",dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode))
{
/* Found a directory,but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else
printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main()
{
// mkdir("/root/senlin",0777);
// chdir("/usr");
// printf("Now the directory is %s\n",getcwd(NULL,NULL));
// rmdir("/root/senlin");
printf("Directory scan of /tmp:\n");
printdir("/tmp",0);
printf("Done\n");
exit(0);
}
变成一个更有用的目录浏览程序:
int main()
{
char *topdir = ".";
if (argc >= 2)
topdir=argv[1];
printf("Directory scan of %s\n",topdir);
printdir(topdir,0);
printf("Done\n");
exit(0);
}
阅读(1121) | 评论(0) | 转发(0) |