Repository navigation
Expand file tree
/
Copy pathfile.c
More file actions
93 lines (78 loc) · 2.02 KB
/
Copy pathfile.c
File metadata and controls
93 lines (78 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "memory.h"
#include "io.h"
#include "file.h"
char *path_dirs[MAX_PATH_DIRS];
int path_dir_count = 0;
char* expand_home_directory(const char* path) {
if (path[0] == '~') {
const char* home = getenv("HOME");
if (home == NULL) {
ffprintln(stderr, "Could not get HOME environment variable.");
return NULL;
}
size_t len = strlen(home) + strlen(path);
char* expanded_path = (char*)rmalloc(len);
snprintf(expanded_path, len, "%s%s", home, path + 1);
return expanded_path;
}
return rstrdup(path);
}
int ensure_directory_exist(const char *dir_path) {
struct stat st;
char* expanded_path = expand_home_directory(dir_path);
if (stat(expanded_path, &st) == 0 && S_ISDIR(st.st_mode)) {
rfree(expanded_path);
return 0;
}
char *parent_path = rstrdup(expanded_path);
char *last_slash = strrchr(parent_path, '/');
if (last_slash != NULL && last_slash != parent_path) {
*last_slash = '\0';
ensure_directory_exist(parent_path);
}
if (mkdir(expanded_path, 0755) != 0) {
if (errno != EEXIST) {
perror("mkdir failed");
rfree(parent_path);
rfree(expanded_path);
return -1;
}
}
rfree(parent_path);
rfree(expanded_path);
return 0;
}
int ensure_file_exist(const char *file_path) {
char* expanded_path = expand_home_directory(file_path);
int fd = open(expanded_path, O_CREAT | O_EXCL, 0644);
if (fd == -1) {
if (errno == EEXIST) {
return 0;
} else {
perror("open failed");
return -1;
}
}
close(fd);
rfree(expanded_path);
return 0;
}
void parse_path() {
char *path = getenv("PATH");
if (!path) return;
char *path_copy = strdup(path);
char *token = strtok(path_copy, ":");
while (token != NULL && path_dir_count < MAX_PATH_DIRS) {
path_dirs[path_dir_count++] = strdup(token);
token = strtok(NULL, ":");
}
free(path_copy);
}