2016-11-07 21:29:30 +00:00
|
|
|
#include "ipfs/os/utils.h"
|
2016-10-27 18:11:34 +00:00
|
|
|
|
2016-10-31 16:13:42 +00:00
|
|
|
#include <unistd.h>
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <pwd.h>
|
|
|
|
#include <unistd.h>
|
2016-11-17 20:07:59 +00:00
|
|
|
#include <stdio.h>
|
2016-10-31 16:13:42 +00:00
|
|
|
|
2016-10-27 18:11:34 +00:00
|
|
|
/**
|
|
|
|
* get an environment varible from the os
|
|
|
|
* @param variable the variable to look for
|
|
|
|
* @returns the results
|
|
|
|
*/
|
2016-11-17 20:07:59 +00:00
|
|
|
char* os_utils_getenv(const char* variable) {
|
2016-10-27 18:11:34 +00:00
|
|
|
return getenv(variable);
|
|
|
|
}
|
|
|
|
|
2016-10-31 16:13:42 +00:00
|
|
|
/**
|
|
|
|
* returns the user's home directory
|
|
|
|
* @returns the home directory
|
|
|
|
*/
|
|
|
|
char* os_utils_get_homedir() {
|
|
|
|
struct passwd *pw = getpwuid(getuid());
|
|
|
|
return pw->pw_dir;
|
|
|
|
}
|
|
|
|
|
2016-10-27 18:11:34 +00:00
|
|
|
/**
|
|
|
|
* join 2 pieces of a filepath, being careful about the slashes
|
|
|
|
* @param root the root part
|
|
|
|
* @param extension what should be concatenated
|
|
|
|
* @param results where to put the results
|
|
|
|
* @param max_len throw an error if the total is longer than max_len
|
|
|
|
*/
|
2016-11-17 20:07:59 +00:00
|
|
|
int os_utils_filepath_join(const char* root, const char* extension, char* results, unsigned long max_len) {
|
2016-10-27 18:11:34 +00:00
|
|
|
if (strlen(root) + strlen(extension) + 1 > max_len)
|
|
|
|
return 0;
|
|
|
|
strncpy(results, root, strlen(root) + 1);
|
2016-11-17 20:07:59 +00:00
|
|
|
// one of these should have a slash. If not, add one
|
|
|
|
if (root[strlen(root)-1] != '/' && extension[0] != '/') {
|
|
|
|
results[strlen(root)] = '/';
|
|
|
|
results[strlen(root)+1] = 0;
|
|
|
|
}
|
2016-10-27 18:11:34 +00:00
|
|
|
strncat(results, extension, strlen(extension)+1);
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2016-11-17 20:07:59 +00:00
|
|
|
int os_utils_file_exists(const char* file_name) {
|
2016-10-27 18:11:34 +00:00
|
|
|
if (access(file_name, F_OK) != -1)
|
|
|
|
return 1;
|
|
|
|
return 0;
|
|
|
|
}
|
2016-10-31 16:13:42 +00:00
|
|
|
|
2016-11-28 13:09:00 +00:00
|
|
|
int os_utils_directory_exists(const char* directory_name) {
|
|
|
|
if (access(directory_name, F_OK) != -1)
|
|
|
|
return 1;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2016-11-17 20:07:59 +00:00
|
|
|
int os_utils_directory_writeable(const char* path) {
|
2016-11-10 13:28:51 +00:00
|
|
|
int result = access(path, W_OK);
|
2016-10-31 16:13:42 +00:00
|
|
|
return result == 0;
|
|
|
|
}
|
2016-11-17 20:07:59 +00:00
|
|
|
|
|
|
|
int os_utils_file_size(const char* path) {
|
|
|
|
// open file
|
|
|
|
FILE* in_file = fopen(path, "r");
|
|
|
|
// determine size
|
|
|
|
fseek(in_file, 0L, SEEK_END);
|
|
|
|
size_t file_size = ftell(in_file);
|
|
|
|
fclose(in_file);
|
|
|
|
return file_size;
|
|
|
|
}
|