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?
The mkdir() function creates a new, empty directory with name filename.
The mkdir function creates a new, empty directory with name filename . The argument mode specifies the file permissions for the new directory file. See The Mode Bits for Access Permission, for more information about this. Write permission is denied for the parent directory in which the new directory is to be added.
We use the mkdir() method of the File class to create a new folder. For creating a directory, we first have to create an instance of the File class and pass a parameter to that instance. This parameter is the path of the directory where we need to create it.
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.
You can use mkdir:
$ man 2 mkdir
#include <sys/stat.h> #include <sys/types.h> int result = mkdir("/home/me/test.txt", 0777);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With