我们来简要模拟一下linux中的ls命令, 代码如下:
#include <stdio.h>
#include <dirent.h> // DIR,struct dirent,opendir, readdir
int main(int argc, char *argv[])
{
printf("%d\n", getppid());
DIR *dp; // 指向目录
struct dirent *dirp; // 指向目录中的对象
if(argc != 2)
{
printf("error\n");
return 1;
}
// 打开一个目录
if((dp = opendir(argv[1])) == NULL)
{
printf("can`t open %s\n", argv[1]);
return 1;
}
// 读取目录中的对象, 然后打印出其名字d_name
while((dirp = readdir(dp)) != NULL)
{
printf("%s\n", dirp->d_name);
}
closedir(dp); // 关闭目录
return 0;
}
运行结果如下:
[taoge@localhost learn_c]$ ls
test.c
[taoge@localhost learn_c]$ echo $$
2812
[taoge@localhost learn_c]$ gcc test.c
[taoge@localhost learn_c]$ ./a.out /home/taoge/Desktop
2812
.
learn_c
..
[taoge@localhost learn_c]$
test.c
[taoge@localhost learn_c]$ echo $$
2812
[taoge@localhost learn_c]$ gcc test.c
[taoge@localhost learn_c]$ ./a.out /home/taoge/Desktop
2812
.
learn_c
..
[taoge@localhost learn_c]$