io: implement stat'ing paths, files, and directory contents

This commit is contained in:
2025-02-14 22:06:24 +00:00
parent 61848aadd7
commit bf83831cee
9 changed files with 257 additions and 46 deletions

View File

@@ -1,9 +1,15 @@
#include "status.h"
#include <blue/core/stringstream.h>
#include <blue/io/file.h>
#include <blue/io/path.h>
#include <blue/object/string.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
struct b_path {
@@ -60,12 +66,13 @@ struct b_path *b_path_create_root()
struct b_path *b_path_create_cwd()
{
char *buf = malloc(_PC_PATH_MAX);
const long buf_len = 2048;
char *buf = malloc(buf_len);
if (!buf) {
return NULL;
}
if (!getcwd(buf, _PC_PATH_MAX)) {
if (!getcwd(buf, buf_len)) {
free(buf);
return NULL;
}
@@ -170,17 +177,68 @@ bool b_path_is_absolute(const struct b_path *path)
bool b_path_exists(const struct b_path *path)
{
return false;
b_file_info info;
if (!B_OK(b_path_stat(path, &info))) {
return false;
}
return true;
}
bool b_path_is_file(const struct b_path *path)
{
return false;
b_file_info info;
if (!B_OK(b_path_stat(path, &info))) {
return false;
}
return (info.attrib & B_FILE_ATTRIB_NORMAL) != 0;
}
bool b_path_is_directory(const struct b_path *path)
{
return false;
b_file_info info;
if (!B_OK(b_path_stat(path, &info))) {
return false;
}
return (info.attrib & B_FILE_ATTRIB_DIRECTORY) != 0;
}
enum b_status b_path_stat(const b_path *path, struct b_file_info *out)
{
struct stat st;
int err = stat(b_path_ptr(path), &st);
if (err != 0) {
return b_status_from_errno(errno, B_ERR_IO_FAILURE);
}
memset(out, 0x0, sizeof *out);
out->length = st.st_size;
if (S_ISREG(st.st_flags)) {
out->attrib |= B_FILE_ATTRIB_NORMAL;
}
if (S_ISDIR(st.st_flags)) {
out->attrib |= B_FILE_ATTRIB_DIRECTORY;
}
if (S_ISBLK(st.st_flags)) {
out->attrib |= B_FILE_ATTRIB_BLOCK_DEVICE;
}
if (S_ISCHR(st.st_flags)) {
out->attrib |= B_FILE_ATTRIB_CHAR_DEVICE;
}
if (S_ISLNK(st.st_flags)) {
out->attrib |= B_FILE_ATTRIB_SYMLINK;
}
return B_SUCCESS;
}
const char *b_path_ptr(const struct b_path *path)
@@ -195,7 +253,9 @@ size_t b_path_length(const struct b_path *path)
void path_release(struct b_object *obj)
{
b_path_release((struct b_path *)obj);
struct b_path *path = (struct b_path *)obj;
b_string_release(path->pathstr);
}
void path_to_string(struct b_object *obj, struct b_stringstream *out)