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?

3

4 Answers

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> struct stat st = {0}; if (stat("/some/directory", &st) == -1) { mkdir("/some/directory", 0700); } 

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.

12

You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h> #include <sys/types.h> int result = mkdir("/home/me/test.txt", 0777); 
5

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

int mkdir (const char *filename, mode_t mode)

#include <sys/types.h> #include <errno.h> #include <string.h> if (mkdir("/some/directory", S_IRWXU | S_IRWXG | S_IRWXO) == -1) { printf("Error: %s\n", strerror(errno)); } 

For best practice it is recommended to use an integer-alias for mode. The argument mode specifies the file permissions for the new directory.

Read + Write + Execute: S_IRWXU (User), S_IRWXG (Group), S_IRWXO (Others)

Source:

If you want to know that the directory exists, lookup the errno's for EEXIST.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy