最近打算学学linux,看了看基础的介绍感觉不明所以,目前在看《Linux程序设计》,看到第三章一个显示目录的程序,感觉C语言和linux简直是天作之合,C语言提供很多底层的函数和一些库函数,可以进行很多方便操作。再和SHELL配合起来对linux编程,确实很爽呀。
记录一下今天的代码:
#include<unistd.h>
#include<stdio.h>
#include<dirent.h>
#include<string.h>
#include<sys/stat.h>
#include<stdlib.h>
void printdir(char *dir, int depth);
int main(int argc, char *argv[]) // 通过参数传递要显示的目录
{
char *topdir = ".";
if( argc >= 2 )
{
topdir = argv[1];
}
printf("Directory scan of %s\n", topdir);
printdir(topdir,0);
printf("done\n");
return 0;
}
void printdir(char *dir, int depth) // depth表示每一层目录的缩进长度
{
DIR *dp; // 指向打开的目录
struct dirent *entry; // dirent结构体的指针,指向读取目录中的每一个条目
struct stat statbuf; // 存储目录中每个条目的状态信息
if ((dp = opendir(dir)) == NULL) //判读是否正确打开目录
{
fprintf(stderr,"cannot open the directory: %s \n", dir);
return;
}
chdir(dir); // 进入指定显示的目录
while((entry = readdir(dp)) != NULL)
{
lstat(entry->d_name, &statbuf);
if(S_ISDIR(statbuf.st_mode)) //判断当前目录中的条目是否是是一个目录,如果是就递归调用当前函数
{
if(strcmp(".", entry->d_name) == 0
| strcmp("..", entry->d_name) == 0)
{
continue;
}
printf("%*s%s/\n", depth, "", entry->d_name); //显示目录的名字,注意%*s的意义
printdir(entry->d_name, depth+4);
}
else // 如果不是目录就直接显示该条目名字
{
printf("%*s%s/\n", depth, "", entry->d_name);
}
}
chdir(".."); //结束递归
closedir(dp);
}