std.c (1843B)
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 void lq_close(int fd) { 36 close(fd); 37 } 38 39 static int fltr_files(const struct dirent *d) { 40 int r; 41 if (*((char*)d->d_name) == '.') { 42 return 0; 43 } 44 return (d->d_type & (DT_LNK | DT_REG)) > 0 ? 1 : 0; 45 return r; 46 } 47 48 /** 49 * \todo scandir calls malloc, so lq_alloc needs malloc alias that maps to it. 50 */ 51 int lq_files(const char *path, char **files, size_t files_len) { 52 int r; 53 int i; 54 struct dirent **ls; 55 56 r = 0; 57 r = scandir(path, &ls, fltr_files, alphasort); 58 if (r < 0) { 59 return -1; 60 } 61 if (r > files_len + 1) { 62 return -2; 63 } 64 for (i = 0; i < r; i++) { 65 *(files+i) = (*(ls+i))->d_name; 66 } 67 *(files+i+1) = NULL; 68 lq_free(ls); 69 return r; 70 } 71 72 int lq_files_pfx(const char *path, char **files, size_t files_len, const char *prefix, char prefix_len) { 73 int r; 74 int i; 75 int c; 76 size_t l; 77 78 c = 0; 79 r = lq_files(path, files, files_len); 80 for (i = 0; i < r; i++) { 81 l = strlen(*(files+i)); 82 if (l < prefix_len) { 83 lq_free(*(files+i)); 84 } 85 if (!lq_cmp(prefix, *(files+i), prefix_len)) { 86 *(files+c) = *(files+i); 87 c++; 88 } 89 *(files+i) = NULL; 90 } 91 for (i = c + 1; i < r; i++) { 92 if (*(files+i) != NULL) { 93 lq_free(*(files+i)); 94 *(files+i) = NULL; 95 } 96 } 97 return c; 98 } 99 100 void lq_files_free(char **files) { 101 int i; 102 103 i = 0; 104 do { 105 if (*(files+i) == NULL) { 106 break; 107 } 108 lq_free(*(files+i)); 109 } while(++i); 110 }