#include #include #include #include #include #include #include #include #include #include #include "cms_util.h" int cms_util_file_exists(char* fname) { int f = open(fname, O_RDONLY); close(f); if (errno == ENOENT) return 0; else return 1; } cms_err cms_util_file_create(char* fname) { int f = open(fname, O_CREAT); close(f); if (f == -1) return cms_err_from_std_err(errno); else return CMS_ERR_NONE; } cms_err cms_util_file_copy(char* fname1, char* fname2) { int f1 = open(fname1, O_RDONLY); int f2 = open(fname2, O_WRONLY); struct stat* s = malloc(sizeof(struct stat)); if (s == NULL) return CMS_ERR_ALLOC; fstat(f1, s); void* buf = malloc(s->st_size); if (buf == NULL) return CMS_ERR_ALLOC; read(f1, buf, s->st_size); write(f2, buf, s->st_size); close(f1); close(f2); free(s); free(buf); return CMS_ERR_NONE; } cms_err cms_util_dir_copy_recursive(char* dir1, char* dir2) { if (mkdir(dir2, 0777) == -1) return cms_err_from_std_err(errno); DIR* dp = opendir(dir1); if (dp == NULL) return cms_err_from_std_err(errno); struct dirent* ep; struct stat* st = malloc(sizeof(struct stat)); if (st == NULL) return CMS_ERR_ALLOC; while (ep = readdir(dp)) { char* path1 = cms_util_path_join(dir1, ep->d_name); char* path2 = cms_util_path_join(dir2, ep->d_name); stat(path1, st); if (S_ISDIR(st->st_mode)) { cms_err err = cms_util_dir_copy_recursive(path1, path2); if (err != CMS_ERR_NONE) return err; } else { cms_err err = cms_util_file_copy(path1, path2); if (err != CMS_ERR_NONE) return err; } } free(st); return 0; } char* cms_util_path_join(char* str1, char* str2) { size_t len1 = strlen(str1); size_t len2 = strlen(str2); if (str1[len1 - 1] == '/') { len1 -= 1; } char* path = malloc((len1 + len2 + 1) * sizeof(char)); if (path == NULL) cms_err_panic(CMS_ERR_ALLOC, ""); if (path == NULL) return NULL; memcpy(path, str1, len1); //First part path[len1] = '/'; //Separator memcpy(path + len1 + 1, str2, len2); //Second part path[len1 + len2 + 1] = '\0'; //Null terminator return path; }