#include "../CgeFs.h" #include #include #include #include #include #include #include #include typedef struct CgeFsDir { DIR *dir; char path[PATH_MAX]; size_t size; } CgeFsDir; static int mapErrno(int value) { switch (value) { case ENOENT: return CGE_FS_ENOENT; case EACCES: return CGE_FS_EACCES; case ENOTDIR: return CGE_FS_ENOTDIR; default: return CGE_FS_EUNKNOWN; } } CgeFsDir *CgeFsOpen(const char *path, int *result) { CgeFsDir *d; DIR *dir; size_t size; dir = opendir(path); if (!dir) { if (result) *result = mapErrno(errno); return NULL; } d = malloc(sizeof(*d)); if (!d) { closedir(dir); if (result) *result = CGE_FS_EUNKNOWN; return NULL; } d->dir = dir; size = strlen(path); if (size < PATH_MAX) { memcpy(d->path, path, size); if (size > 0 && d->path[size - 1] != '/') { d->path[size] = '/'; d->path[size + 1] = 0; d->size = size + 1; } else { memcpy(d->path, path, size); d->path[size] = 0; d->size = size; } } else { d->path[0] = 0; d->size = 0; } return d; } int CgeFsNext(CgeFsDir *d, CgeFsInfo *info, int *result) { struct dirent *ent; struct stat st; char path[PATH_MAX]; while ((ent = readdir(d->dir)) != NULL) { if (!strcmp(ent->d_name, ".")) continue; if (!strcmp(ent->d_name, "..")) continue; if (d->size > 0 && d->size < PATH_MAX - 2) { strncpy(path, d->path, d->size); path[d->size] = '\0'; strncat(path, ent->d_name, PATH_MAX - strlen(path) - 1); } else { strncpy(path, ent->d_name, PATH_MAX - 1); path[PATH_MAX - 1] = '\0'; } if (stat(path, &st) != 0) continue; strncpy(info->name, ent->d_name, CGE_FS_NAME_MAX - 1); info->name[CGE_FS_NAME_MAX - 1] = '\0'; info->type = S_ISDIR(st.st_mode) ? CGE_FS_DIR : CGE_FS_FILE; info->size = (uint64_t)st.st_size; info->mtime = (uint64_t)st.st_mtime; if (result) *result = CGE_FS_EOK; return 1; } return 0; } void CgeFsClose(CgeFsDir *d) { if (!d) return; closedir(d->dir); free(d); } int CgeFsCreateDir(const char *path, int *result) { if (mkdir(path, 0777) != 0) { if (result) *result = mapErrno(errno); return 0; } return 1; } int CgeFsRemoveDir(const char *path, int *result) { if (rmdir(path) != 0) { if (result) *result = mapErrno(errno); return 0; } return 1; }