×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to create a directory using mkdir() function

Here, we are going to learn how to create a directory using mkdir() function using C program?
Submitted by Nidhi, on August 14, 2021

Problem statement

Input the name (path) of the directory, and then we will create the given directory using the mkdir() function.

Create a directory in C

The mkdir() function is library function of <sys/stat.h> header file which is used to create a new directory with a new path.

Syntax

int mkdir(const char *path, mode_t mode);

The argument path defines the path of the directory, and the mode specifies the file permissions for the new directory file.

The function returns 0 if the directory created successfully, or -1 on failure.

C program to create a directory using mkdir() function

The source code to create a directory using the mkdir() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to create a directory
// using mkdir() function

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main()
{
    char dirName[16];
    int ret = 0;

    printf("Enter directory name: ");
    scanf("%s", dirName);

    ret = mkdir(dirName, 0755);

    if (ret == 0)
        printf("Directory created successfully\n");
    else
        printf("Unable to create directory %s\n", dirName);

    return 0;
}

Output

Enter directory name: temp
Directory created successfully

Explanation

Here, we created a character array dirName. Then we read the name of the directory from the user. Then we created the given directory using the mkdir() function and printed the appropriate message on the console screen.

C File Handling Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.