fs_posix.c (1906B)
1 #include "fs_posix.h" 2 3 #include <errno.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <sys/stat.h> 8 #include <unistd.h> 9 10 #include "utils.h" 11 12 static int posix_mkdir(const char* path, mode_t mode) { 13 return mkdir(path, mode); 14 } 15 16 static int posix_mkdirp(const char* path) { 17 char* mut_path = estrdup(path); 18 19 for (char* p = mut_path + (mut_path[0] == '/'); *p; p++) { 20 if (*p != '/') { 21 continue; 22 } 23 *p = '\0'; 24 if (mkdir(mut_path, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) { 25 free(mut_path); 26 return -1; 27 } 28 *p = '/'; 29 } 30 if (mkdir(mut_path, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) { 31 free(mut_path); 32 return -1; 33 } 34 35 free(mut_path); 36 return 0; 37 } 38 39 static FILE* posix_fopen(const char* path, const char* mode) { 40 return fopen(path, mode); 41 } 42 43 static FILE* posix_fdopen(int fd, const char* mode) { 44 return fdopen(fd, mode); 45 } 46 47 static int posix_fclose(FILE* stream) { 48 return fclose(stream); 49 } 50 51 static int posix_close(int fd) { 52 return close(fd); 53 } 54 55 static int posix_mkstemp(char* template) { 56 return mkstemp(template); 57 } 58 59 static int posix_rename(const char* oldpath, const char* newpath) { 60 return rename(oldpath, newpath); 61 } 62 63 static int posix_chmod(const char* path, mode_t mode) { 64 return chmod(path, mode); 65 } 66 67 static int posix_access(const char* path, int amode) { 68 return access(path, amode); 69 } 70 71 static char* posix_realpath(const char* path, char* resolved_path) { 72 return realpath(path, resolved_path); 73 } 74 75 static const FileSystem kStdPosixFs = { 76 77 .mkdir = posix_mkdir, 78 .mkdirp = posix_mkdirp, 79 .fopen = posix_fopen, 80 .fdopen = posix_fdopen, 81 .fclose = posix_fclose, 82 .close = posix_close, 83 .mkstemp = posix_mkstemp, 84 .rename = posix_rename, 85 .chmod = posix_chmod, 86 .access = posix_access, 87 .realpath = posix_realpath, 88 }; 89 90 const FileSystem* g_fs_posix = &kStdPosixFs;