文件IO-opendir-readdir-fdopendir-rewinddir-closedir-dirfd

第一版

/*
	Linux API:
	实现 ls command
*/
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc , char* argv[])
{
    DIR * dir;					// DIR结构体,类似FILE
	/*
		struct __dirstream   
		{   
		void *__fd;    
		char *__data;    
		int __entry_data;    
		char *__ptr;    
		int __entry_ptr;    
		size_t __allocation;    
		size_t __size;    
		__libc_lock_define (, __lock)    
		};   
		typedef struct __dirstream DIR; 
	*/
    struct dirent * ptr;		
	/*
		struct dirent
		{
		   long d_ino; 					// inode number 索引节点号 
		   off_t d_off; 				// offset to this dirent 在目录文件中的偏移 
		   unsigned short d_reclen; 	// length of this d_name 文件名长 
		   unsigned char d_type; 		// the type of d_name 文件类型 
		   char d_name [NAME_MAX+1]; 	// file name (null-terminated) 文件名,最长255字符 
		}
		
		d : 目录-4
		- : 文件-8
		l : 链接文件
	*/
    dir = opendir("./");		// 打开目录
    while((ptr = readdir(dir)) != NULL)			// 读取目录,struct dirent* readdir(DIR* dir_handle);
    {
        printf("d_name : %s\n", ptr->d_name);
		printf("d_type : %d\n", ptr->d_type);
    }
	
	closedir(dir);				// 关闭打开的目录指针
	return 0;
}

makefile

cshell:code.o
	gcc -o cshell code.o
code.o:code.c
	gcc -c code.c
.PHONY: clean
clean:
	rm -f *.o
	rm -f cshell
posted @ 2022-10-31 20:58  steve的miao  阅读(17)  评论(0编辑  收藏  举报