Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new directory in C

Tags:

c

linux

directory

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?

like image 855
Jeegar Patel Avatar asked Sep 15 '11 11:09

Jeegar Patel


People also ask

How do you create a directory in C?

The mkdir() function creates a new, empty directory with name filename.

How does mkdir work in C?

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.

What is used to create a new directory?

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.


2 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.

like image 176
Arnaud Le Blanc Avatar answered Sep 23 '22 15:09

Arnaud Le Blanc


You can use mkdir:

$ man 2 mkdir

#include <sys/stat.h> #include <sys/types.h>  int result = mkdir("/home/me/test.txt", 0777); 
like image 29
Paul R Avatar answered Sep 22 '22 15:09

Paul R