116 lines
2.3 KiB
C
116 lines
2.3 KiB
C
#define _POSIX_C_SOURCE 200112L
|
|
#include "../CgeFs.h"
|
|
#include <errno.h>
|
|
#include <limits.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/types.h>
|
|
#include <unistd.h>
|
|
|
|
static int mapErrno(int err) {
|
|
switch (err) {
|
|
case ENOENT:
|
|
return CGE_FS_ENOENT;
|
|
|
|
case EEXIST:
|
|
return CGE_FS_EEXIST;
|
|
|
|
case EACCES:
|
|
return CGE_FS_EACCES;
|
|
|
|
case ENOTDIR:
|
|
return CGE_FS_ENOTDIR;
|
|
|
|
case EMFILE:
|
|
return CGE_FS_EMFILE;
|
|
|
|
case ENAMETOOLONG:
|
|
return CGE_FS_ENAMETOOLONG;
|
|
|
|
case EIO:
|
|
return CGE_FS_EIO;
|
|
|
|
default:
|
|
return CGE_FS_EUNKNOWN;
|
|
}
|
|
}
|
|
|
|
int CgeFsStat(const char *path, CgeFsInfo *info, int *result) {
|
|
struct stat st;
|
|
const char *p;
|
|
const char *base;
|
|
|
|
if (stat(path, &st) != 0) {
|
|
if (result)
|
|
*result = mapErrno(errno);
|
|
return 0;
|
|
}
|
|
|
|
base = NULL;
|
|
for (p = path; *p; p++)
|
|
if (*p == '/') base = p + 1;
|
|
|
|
if (!base)
|
|
base = path;
|
|
|
|
strncpy(info->name, base, 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;
|
|
return 1;
|
|
}
|
|
|
|
int CgeFsDelete(const char *path, int *result) {
|
|
if (unlink(path) != 0) {
|
|
if (result)
|
|
*result = mapErrno(errno);
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
int CgeFsRename(const char *from, const char *to, int *result) {
|
|
if (rename(from, to) != 0) {
|
|
if (result)
|
|
*result = mapErrno(errno);
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
int CgeFsCopy(const char *from, const char *to, int *result) {
|
|
FILE *fin, *fout;
|
|
char buf[PATH_MAX];
|
|
size_t n;
|
|
|
|
if (!(fin = fopen(from, "rb"))) {
|
|
if (result)
|
|
*result = mapErrno(errno);
|
|
return 0;
|
|
}
|
|
|
|
if (!(fout = fopen(to, "wb"))) {
|
|
fclose(fin);
|
|
if (result)
|
|
*result = mapErrno(errno);
|
|
return 0;
|
|
}
|
|
|
|
while ((n = fread(buf, 1, sizeof(buf), fin)) > 0) {
|
|
if (fwrite(buf, 1, n, fout) != n) {
|
|
if (result)
|
|
*result = CGE_FS_EIO;
|
|
fclose(fin);
|
|
fclose(fout);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
fclose(fin);
|
|
fclose(fout);
|
|
return 1;
|
|
}
|