今天,揭开linux ls-a背后的代码。
1.引用头文件:#include<dirent.h>
今天要先了解包含在其中的两个结构体
1
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; //DIR就是
struct __dirstream 这个结构体
2
struct dirent {
long d_ino;
off_t d_off;
unsigned short d_reclen;
char d_name [NAME_MAX+1]; 文件名,其他自行搜查 }
2.了解要用到的函数,也需包含在那个头文件中
1.opendir:函数用于打开一个目录,并返回指向该目录的句柄(也就是指向该目录信息的指针),该结构体指针指向上面的第一个结构体
DIR *opendir(const char *name);
name:指定需要打开的目录路径名
返回值:成功将返回指向该目录的句柄,一个 DIR 指针,否则是NULL
2.readdir:读取目录,获取目录下所有文件的名称以及对应 inode 号等
struct dirent *readdir(DIR *dirp);
dirp:目录句柄 DIR 指针,也就是调用opendir函数返回的指针 返回值:返回一个指向 struct dirent 结构体(上面的第二个结构体)的指针,在到达目录流的末尾(把目录下的文件读完)或发生错误时,它返回 NULL。
3.closedir:函数用于关闭处于打开状态的目录,同时释放它所使用的资源
int closedir(DIR *dirp);
dirp:目录句柄 DIR 指针,也就是调用opendir函数返回的指针
返回值:成功返回 0;失败将返回-1
下面展示代码
#include <stdio.h> #include <dirent.h> #include<string.h> int main() { DIR *dir; struct dirent *entry; // 打开目录流 dir = opendir(".");//"."指的就是当前目录下的目录流 // 检查目录流是否成功打开 if (dir == NULL) { perror("opendir");//打印opendir函数相关的错误信息 return 1;//相当于exit(EXIT_FAILURE)退出程序 } // 读取目录中的文件和子目录 while ((entry = readdir(dir)) != NULL) { printf("%s\n", entry->d_name); } // 关闭目录流 closedir(dir);//你也可以写的更细,判断是否关闭成功 return 0; }
展示结果
ls ls -a . .. 1.c 2.c ls ls-a ls-a.c ls gcc ls-a.c -o ls-a ➜ ls ./ls-a ls-a.c 1.c ls ls-a 2.c .. .
~~虽然我走得很慢,但绝不停止前行的步伐。加油!