std.c (2080B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <fcntl.h> 4 #include <unistd.h> 5 #include <dirent.h> 6 #include <string.h> 7 #include <errno.h> 8 #include <sys/stat.h> 9 10 #include "lq/mem.h" 11 12 13 char *mktempdir(char *s) { 14 return mkdtemp(s); 15 } 16 17 char *ensuredir(char *s) { 18 int r; 19 20 r = mkdir(s, S_IRWXU); 21 if (r && r != EEXIST) { 22 return NULL; 23 } 24 return s; 25 } 26 27 int lq_open(const char *pathname, int flags, int mode) { 28 return open(pathname, flags, (mode_t)mode); 29 } 30 31 int lq_read(int f, void *buf, size_t c) { 32 return read(f, buf, c); 33 } 34 35 int lq_write(int f, void *buf, size_t c) { 36 return write(f, buf, c); 37 } 38 39 void lq_close(int fd) { 40 close(fd); 41 } 42 43 static int fltr_files(const struct dirent *d) { 44 int r; 45 if (*((char*)d->d_name) == '.') { 46 return 0; 47 } 48 return (d->d_type & (DT_LNK | DT_REG)) > 0 ? 1 : 0; 49 return r; 50 } 51 52 /** 53 * \todo scandir calls malloc, so lq_alloc needs malloc alias that maps to it. 54 * \todo strdup doubles the mem needed for the iteration, instead need to keep scandir state and release after treatment 55 */ 56 int lq_files(const char *path, char **files, size_t files_len) { 57 int r; 58 int i; 59 struct dirent **ls; 60 61 r = 0; 62 r = scandir(path, &ls, fltr_files, alphasort); 63 if (r < 0) { 64 return -1; 65 } 66 if (r > files_len + 1) { 67 return -2; 68 } 69 for (i = 0; i < r; i++) { 70 //*(files+i) = (*(ls+i))->d_name; 71 *(files+i) = strdup((*(ls+i))->d_name); 72 } 73 *(files+i+1) = NULL; 74 lq_free(ls); 75 return r; 76 } 77 78 int lq_files_pfx(const char *path, char **files, size_t files_len, const char *prefix, char prefix_len) { 79 int r; 80 int i; 81 int c; 82 size_t l; 83 84 c = 0; 85 r = lq_files(path, files, files_len); 86 for (i = 0; i < r; i++) { 87 l = strlen(*(files+i)); 88 if (l < prefix_len) { 89 lq_free(*(files+i)); 90 } 91 if (!lq_cmp(prefix, *(files+i), prefix_len)) { 92 *(files+c) = *(files+i); 93 c++; 94 } 95 *(files+i) = NULL; 96 } 97 for (i = c + 1; i < r; i++) { 98 if (*(files+i) != NULL) { 99 lq_free(*(files+i)); 100 *(files+i) = NULL; 101 } 102 } 103 return c; 104 } 105 106 void lq_files_free(char **files) { 107 int i; 108 109 i = 0; 110 do { 111 if (*(files+i) == NULL) { 112 break; 113 } 114 lq_free(*(files+i)); 115 } while(++i); 116 }