70 lines
2.0 KiB
C
Raw Normal View History

2025-03-16 07:36:13 +01:00
// Written by retoor@molodetz.nl
// This header file contains utility functions for manipulating file system paths, focusing primarily on expanding paths starting with '~' to the home directory.
// This code uses standard libraries: stdio.h, stdlib.h, and string.h, and conditionally includes the posix libraries pwd.h and unistd.h when expanding the home directory manually.
// MIT License
//
// Permission is granted to use, copy, modify, merge, distribute, sublicense, and/or sell copies of the Software.
// The license includes conditions about providing a copy of the license and the limitation of liability and warranty.
#ifndef UTILS_H
#define UTILS_H
2025-03-28 02:41:15 +01:00
#include <unistd.h>
2025-03-16 07:36:13 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* expand_home_directory(const char* path) {
if (path == NULL) return NULL;
if (path[0] == '~' && path[1] == '/') {
const char* home_dir = getenv("HOME");
if (home_dir == NULL) {
#include <pwd.h>
#include <unistd.h>
struct passwd* pw = getpwuid(getuid());
if (pw == NULL) return NULL;
home_dir = pw->pw_dir;
}
size_t home_len = strlen(home_dir);
size_t path_len = strlen(path) - 1;
char* expanded_path = malloc(home_len + path_len + 1);
if (expanded_path == NULL) return NULL;
strcpy(expanded_path, home_dir);
strcat(expanded_path, path + 1);
return expanded_path;
} else {
return strdup(path);
}
}
2025-03-16 22:46:09 +01:00
char * read_file(const char * path) {
char * expanded_path = expand_home_directory(path);
FILE *file = fopen(expanded_path, "r");
free(expanded_path);
if (file == NULL) {
return NULL;
}
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
char *buffer = (char *)malloc(size + 1);
size_t read = fread(buffer, 1, size, file);
if (read == 0) {
free(buffer);
return NULL;
}
2025-03-16 07:36:13 +01:00
2025-03-16 22:46:09 +01:00
fclose(file);
buffer[read] = '\0';
return buffer;
}
#endif