部分完成了readdir

This commit is contained in:
fslongjin
2022-05-27 13:41:10 +08:00
parent 156c2c2389
commit a4157bb4a7
10 changed files with 385 additions and 12 deletions

View File

@ -35,4 +35,7 @@ ctype.o: ctype.c
gcc $(CFLAGS) -c ctype.c -o ctype.o
string.o: string.c
gcc $(CFLAGS) -c string.c -o string.o
gcc $(CFLAGS) -c string.c -o string.o
dirent.o: dirent.c
gcc $(CFLAGS) -c dirent.c -o dirent.o

71
user/libs/libc/dirent.c Normal file
View File

@ -0,0 +1,71 @@
#include "dirent.h"
#include "unistd.h"
#include "stdio.h"
#include "fcntl.h"
#include "stddef.h"
#include "stdlib.h"
#include "string.h"
#include <libsystem/syscall.h>
/**
* @brief 打开文件夹
*
* @param dirname
* @return DIR*
*/
struct DIR *opendir(const char *path)
{
int fd = open(path, O_DIRECTORY);
if (fd < 0) // 目录打开失败
return NULL;
// 分配DIR结构体
struct DIR *dirp = (struct DIR *)malloc(sizeof(struct DIR));
memset(dirp, 0, sizeof(struct DIR));
dirp->fd = fd;
dirp->buf_len = DIR_BUF_SIZE;
dirp->buf_pos = 0;
return dirp;
}
/**
* @brief 关闭文件夹
*
* @param dirp DIR结构体指针
* @return int 成功0 失败:-1
+--------+--------------------------------+
| errno | 描述 |
+--------+--------------------------------+
| 0 | 成功 |
| -EBADF | 当前dirp不指向一个打开了的目录 |
| -EINTR | 函数执行期间被信号打断 |
+--------+--------------------------------+
*/
int closedir(struct DIR *dirp)
{
int retval = close(dirp->fd);
free(dirp);
return retval;
}
int64_t getdents(int fd, struct dirent *dirent, long count)
{
return syscall_invoke(SYS_GET_DENTS, fd, (uint64_t)dirent, count, 0, 0, 0, 0, 0);
}
/**
* @brief 从目录中读取数据
*
* @param dir
* @return struct dirent*
*/
struct dirent *reaaddir(struct DIR *dir)
{
memset(dir, 0, DIR_BUF_SIZE);
int len = getdents(dir->fd, (struct dirent *)dir->buf, DIR_BUF_SIZE);
if (len > 0)
return (struct dirent *)dir->buf;
else
return NULL;
}

57
user/libs/libc/dirent.h Normal file
View File

@ -0,0 +1,57 @@
#pragma once
#include <libc/sys/types.h>
#define DIR_BUF_SIZE 256
/**
* @brief 文件夹结构体
*
*/
struct DIR
{
int fd;
int buf_pos;
int buf_len;
char buf[DIR_BUF_SIZE];
// todo: 加一个指向dirent结构体的指针
};
struct dirent
{
ino_t d_ino; // 文件序列号
off_t d_off; // dir偏移量
unsigned short d_reclen; // 目录下的记录数
unsigned char d_type; // entry的类型
char d_name[256]; // 文件entry的名字
};
/**
* @brief 打开文件夹
*
* @param dirname
* @return DIR*
*/
struct DIR *opendir(const char *dirname);
/**
* @brief 关闭文件夹
*
* @param dirp DIR结构体指针
* @return int 成功0 失败:-1
+--------+--------------------------------+
| errno | 描述 |
+--------+--------------------------------+
| 0 | 成功 |
| -EBADF | 当前dirp不指向一个打开了的目录 |
| -EINTR | 函数执行期间被信号打断 |
+--------+--------------------------------+
*/
int closedir(struct DIR *dirp);
/**
* @brief 从目录中读取数据
*
* @param dir
* @return struct dirent*
*/
struct dirent* reaaddir(struct DIR* dir);