Make a Directory with C on Linux

Another quick C post tonight.

Today the project that led me to post this had me finding a way to create directories in C.

The libc library provides this functionality in the form of the mkdir function as shown by info libc:

— Function: int mkdir (const char *FILENAME, mode_t MODE)
The `mkdir’ function creates a new, empty directory with name
FILENAME.

The argument MODE specifies the file permissions for the new
directory file. *Note Permission Bits::, for more information
about this.

A return value of `0′ indicates successful completion, and `-1′
indicates failure. In addition to the usual file name syntax
errors (*note File Name Errors::), the following `errno’ error
conditions are defined for this function:

To use this function, your program should include the header file
`sys/stat.h’.

Here’s some sample code that will take in an argument and create a directory with that name:

#include
#include
int main ( int argc, char *argv[] )
{

if ( argc !=2 )
{
printf( “\nPlease supply a directory name” );
}
else
{
mkdir(argv[1],0777);
}
}

I hope someone is finding my poorly written code useful. I’ve just recently started to work with C and I’ve found that the documentation can be somewhat intimidating for a beginner coming from the sysadmin universe. With any luck these posts can help another admin get started on a quick and dirty C project.