feat(config,utilities): added a function to create a default config
This commit is contained in:
parent
0fbfe09638
commit
8cc5c6310b
2 changed files with 60 additions and 0 deletions
|
|
@ -64,5 +64,7 @@ void combine_path(char*, char*);
|
||||||
PathType get_path_type(const char*);
|
PathType get_path_type(const char*);
|
||||||
char* get_file_content(char*);
|
char* get_file_content(char*);
|
||||||
char* get_file_content_with_size(char*, size_t*);
|
char* get_file_content_with_size(char*, size_t*);
|
||||||
|
int create_default_config_file(char*);
|
||||||
|
|
||||||
|
|
||||||
#endif // UTILITIES_H
|
#endif // UTILITIES_H
|
||||||
|
|
|
||||||
|
|
@ -532,3 +532,61 @@ char* get_file_content_with_size(char* path, size_t* size) {
|
||||||
*size = got;
|
*size = got;
|
||||||
return buf;
|
return buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create directory recursively
|
||||||
|
static int mkdir_recursive(const char *path, mode_t mode) {
|
||||||
|
char *path_copy = strdup(path);
|
||||||
|
if (!path_copy) return -1;
|
||||||
|
|
||||||
|
char *p = path_copy;
|
||||||
|
|
||||||
|
if (*p == '/') p++;
|
||||||
|
|
||||||
|
while (*p) {
|
||||||
|
while (*p && *p != '/') p++;
|
||||||
|
|
||||||
|
char saved = *p;
|
||||||
|
*p = '\0';
|
||||||
|
|
||||||
|
if (mkdir(path_copy, mode) == -1 && errno != EEXIST) {
|
||||||
|
free(path_copy);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
*p = saved;
|
||||||
|
if (*p) p++;
|
||||||
|
}
|
||||||
|
|
||||||
|
free(path_copy);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create default config file
|
||||||
|
int create_default_config_file(char* config_path) {
|
||||||
|
char *dir_path = strdup(config_path);
|
||||||
|
if (!dir_path) return -1;
|
||||||
|
|
||||||
|
char *last_slash = strrchr(dir_path, '/');
|
||||||
|
if (last_slash) {
|
||||||
|
*last_slash = '\0';
|
||||||
|
if (mkdir_recursive(dir_path, 0755) < 0) {
|
||||||
|
perror("mkdir_recursive");
|
||||||
|
free(dir_path);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
free(dir_path);
|
||||||
|
|
||||||
|
FILE *fp = fopen(config_path, "w");
|
||||||
|
if (!fp) {
|
||||||
|
perror("fopen");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
fprintf(fp, "[user]\n");
|
||||||
|
fprintf(fp, "name = \"Your Name\"\n");
|
||||||
|
fprintf(fp, "email = \"your.email@example.com\"\n");
|
||||||
|
|
||||||
|
fclose(fp);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue