linux下ls命令的简要模拟---顺便学学opendir、readdir函数
我们来简要模拟一下linux中的ls命令, 代码如下:
#include <stdio.h>
#include <dirent.h> // DIR,struct dirent,opendir, readdir
int main(int argc, char *argv[])
{
printf("%d
", getppid());
DIR *dp; // 指向目录
struct dirent *dirp; // 指向目录中的对象
if(argc != 2)
{
printf("error
");
return 1;
}
// 打开一个目录
if((dp = opendir(argv[1])) == NULL)
{
printf("can`t open %s
", argv[1]);
return 1;
}
// 读取目录中的对象, 然后打印出其名字d_name
while((dirp = readdir(dp)) != NULL)
{
printf("%s
", dirp->d_name);
}
closedir(dp); // 关闭目录
return 0;
}
运行结果如下:
[taoge@localhost learn_c]$ lstest.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]$
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
