|
| 1 | +#include <stdio.h> |
| 2 | +#include <string.h> |
| 3 | +#include <unistd.h> |
| 4 | + |
| 5 | +#include <linux/limits.h> |
| 6 | + |
| 7 | +#include <sys/types.h> |
| 8 | +#include <sys/stat.h> |
| 9 | + |
| 10 | +#include "s_file.h" |
| 11 | +#include "s_macros.h" |
| 12 | + |
| 13 | +SFile *s_file_create(const char *path, int flag, int mode) |
| 14 | +{ |
| 15 | + int ret; |
| 16 | + size_t path_len; |
| 17 | + SFile *file = NULL; |
| 18 | + struct stat sb; |
| 19 | + |
| 20 | + if S_UNLIKELY (path == NULL) |
| 21 | + return NULL; |
| 22 | + /* |
| 23 | + * Todo |
| 24 | + * If path is not absolute path, |
| 25 | + * It is needs to process about the path not return NULL |
| 26 | + */ |
| 27 | + |
| 28 | + path_len = strlen(path); |
| 29 | + if S_UNLIKELY (path_len > PATH_MAX) |
| 30 | + return NULL; |
| 31 | + |
| 32 | + ret = s_file_is_absolute_path(path); |
| 33 | + if S_UNLIKELY (ret == FALSE) |
| 34 | + return NULL; |
| 35 | + |
| 36 | + ret = lstat(path, &sb); |
| 37 | + if S_UNLIKELY (ret == -1) |
| 38 | + return NULL; |
| 39 | + |
| 40 | + if S_UNLIKELY (!(sb.sb_mode & S_IFREG)) |
| 41 | + return NULL; |
| 42 | + |
| 43 | + file = (SFile *)calloc(1, sizeof(SFile)); |
| 44 | + if S_UNLIKELY (file == NULL) |
| 45 | + return NULL; |
| 46 | + |
| 47 | + file->path = strndup(path, PATH_MAX); |
| 48 | + if S_UNLIKELY (file->path == NULL) { |
| 49 | + s_file_destroy(file); |
| 50 | + return NULL; |
| 51 | + } |
| 52 | + |
| 53 | + file->sb = sb; |
| 54 | + |
| 55 | + file->fd = open(path, flag, mode); |
| 56 | + if (file->fd == -1) { |
| 57 | + s_file_Destroy(file); |
| 58 | + return NULL; |
| 59 | + } |
| 60 | + |
| 61 | + return file; |
| 62 | +} |
| 63 | + |
| 64 | +void s_file_destroy(SFile *file) |
| 65 | +{ |
| 66 | + if S_UNLIKELY (file == NULL) |
| 67 | + return; |
| 68 | + |
| 69 | + if (file->path) |
| 70 | + free(file->path); |
| 71 | + if (file->fd) |
| 72 | + close(file->fd); |
| 73 | + free(file); |
| 74 | + file = NULL; |
| 75 | +} |
| 76 | + |
| 77 | +int s_file_is_absolute_path(const char *path) |
| 78 | +{ |
| 79 | + if S_UNLIEKLY (path == NULL) |
| 80 | + return FALSE; |
| 81 | + |
| 82 | + if (path[0] == '/') |
| 83 | + return TRUE; |
| 84 | + return FALSE; |
| 85 | +} |
0 commit comments