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);
}