I want to write a program that checks for the existence of a directory; if that directory does not exist then it creates the directory and a log file inside of it, but if the directory already exists, then it just creates a new log file in that folder.
How would I do this in C with Linux?
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
I want to write a program that (...) creates the directory and a (...) file inside of it
because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.
void rek_mkdir(char *path) {
char *sep = strrchr(path, '/');
if(sep != NULL) {
*sep = 0;
rek_mkdir(path);
*sep = '/';
}
if(mkdir(path, 0777) && errno != EEXIST)
printf("error while trying to create '%s'\n%m\n", path);
}
FILE *fopen_mkdir(char *path, char *mode) {
char *sep = strrchr(path, '/');
if(sep) {
char *path0 = strdup(path);
path0[ sep - path ] = 0;
rek_mkdir(path0);
free(path0);
}
return fopen(path,mode);
}
Source: Stackoverflow.com