入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

linux下ls命令的简要模拟---顺便学学opendir、readdir函数

创建时间:2015-04-24 投稿人: 浏览次数:3565

     我们来简要模拟一下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]$ 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]$ 


     顺便说一下, 当前shell是一个运行的进程, 它的pid是2812,  ./a.out对应的进程实际上是shell进程的子进程, 从上述结果也可以看得出来。  在上面的模拟中, 我们的a.out实际上就是系统的ls

  

    



声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。