×

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a directory that is inside the root directory and can include other subdirectories. You can quickly present different types of files and subdirectories that are present in a directory using the computer language.

Creating Directories or Folders

At present, we have various operating systems, for example let's talk about Windows and Linux, have other processes for creating directories and files. Additionally, there are several compilers that can be utilized, such as GCC/G++ compilers for Linux and Turbo C for Windows.

To create directories, the Linux operating system offers the following system call:

#include <sys/stat.h>

The data supplied by the functions fstat(), lstat(), and stat are defined by the header file "sys/stat.h" ().

#include <sys/types.h>

Typedef symbols and structures are defined in the sys/types.h header file.

Syntax: int mkdir(const char *pathname, mode_t mode);

mkdir plays a significant role in creating directories or folders in either c or c++ programming languages.

You can complete this process by utilizing the mkdir() method. This function allows for the creation of directories. A new, empty directory with the name filename is created by the mkdir() method.

The directory name is specified using the 'pathname' option.

The parameter mode specifies the permissions to utilise. The process' umask modifies it as usual: the generated directory's permissions are (mode & umask & 0777). The operating system determines the other mode bits of the newly created directory.

Create Directory/Folder with C/C++ Program

The following program will show how to create a directory/folder with C and C++. This program will create a folder in a specific directory path with the mkdir() function. The mkdir() function accepts an argument which is the name and path of the directory.

C and C++  program to create a directory/folder

Example 1

#include<iosrtream>
#include<direct.h>
using namespace std;
 int main(){
//Creating a new Directory
    if(mkdir("C:/MyFolder") == -1)
        cerr << " Error Occured : " << strerror(errno) << endl;
    else
        cout << "Directory Created";
}

Output

Directory Created

There are some specific header files like #include <sys/types.h> and #include <sys/stat.h> which has to be used while creating a directory in Linux operating system:

Example 2

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


void main() {
   int check;
  char *dirname;
  clrscr();
  printf("Enter a directory path and name to be created (C:/name):");
  gets(dirname);
  check = mkdir(dirname);


  if (!check)
  printf("Directory successfully created\n");


 else
 {
   printf("Unable to create directory\n");
   exit(1);  }
  getch();
  system("dir/p");
  getch();
}

Output

Enter a directory path and name to be created (C:/name): C:/Programs
Directory successfully created.

There are also different methods available to create these directories

Creating Directory by using CreateDirectory Method:

An IOUtils Method called CreateDirectory Method (System.IOUtils.TDirectory.CreateDirectory) as this method is highly helpful in organizing a new directory at the specified path. We can use the CreateDirectory function from the filesystem library to establish a new directory at the specified path. CreateDirectory tries to create the directories specified in the path if they don't already exist.

Here, let's look at a simple example to CreateDirectory() Method:

TDirectory::CreateDirectory( L"D:\\MyFolder");

Creating Directory by using create_directory std::filesystem method:

Create directory() is a method in the C++ standard that was added with C++ 17 standards. As shown in the example below, we can also utilize this function in C++ and C++ Builder apps.

Example

#include <iostream>
#include <filesystem> 
int main()
{
   std::filesystem::create_directory("C:\\MyFolder3");
}

Creating Directory by using with System Commands

You can use the std::system() command to use system commands like cd, mkdir, and rmdir on Windows and some other operating systems. For instance, let's consider mkdir command for it's specific usage to create a folder, the xcopy command to copy it to another folder, and the rmdir command to delete it. See illustration underneath.

Example

#include <iostream>
 int main()
{
    std::system("mkdir D:\\MyFolder");
}

How to access the existing directory or folder

We can get the current directory using the getcwd function.

On many Unix-based systems, a POSIX-compliant function called getcwd can be used to retrieve the current working directory. The function requires two parameters: the size of the buffer and the first char* buffer, which stores the directory path name. As an arbitrary example, observe that we are allocating a 256-element buffer and declaring a char fixed-length array. If the call is successful, reading the char buffer allows printing the current directory's stored name.

Program to access the directory in C/C++:

#include <iostream>
#include <string>
#include <filesystem>
#include <unistd.h>
using namespace std;


int main() 
{
    char temp[256];
    getcwd(temp, 256);
    cout << "Current working directory is: " << temp << endl;


    return EXIT_SUCCESS;
}

Output:

Current working directory: D:/temp/programs

Advantages of creating a directory

The fundamental justification for doing this is that headers are required for compiled libraries in order for the user to consume them. By default, the headers that are available for public consumption are those found in the include directory. There may be internal headers in the source directory, but they are not intended to be shared with the generated library.

Therefore, to use the library, link to the binary and add the include directory to the header paths of your build system. Similarly, you may determine which files need to be transferred to the central location when installing your compiled library and which files don't.

Also, logical groupings of similar headers in the directory hierarchy. You don't need to know every specific of the exact locations of files; only a few directories need to be included in the includes path. Without modifying the code, libraries and the headers that go with them can be updated.

Convenient! You don't have to use the same build environment as I do, but we may frequently achieve almost identical results and reliable construction. Rearranging the paths in an includes macro or environment variable does not affect the header files that are produced during the build; portable structures Simply package everything from the build's root and send it to another developer. Information proximity. You are aware of the header's exact location.


Related Topics

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.