How to Check if a Directory Already Exists in a Qt Widget Application in C++


C++


In this article, we show how to check if a directory already exists within a given directory in a Qt widget application in C++.

So creating a directory is very standard in many programs. Many programs allow for the creation of new directories on a computer. We can then place files or additional directories within this newly created directory.

How can we check to see if that directory already exists before creating a new directory?

Usually it is not intended to overwrite any existing directory. Therefore, we want to check first to see if that directory exists. If it does, we don't create the directory. If it doesn't exist, then we go ahead and create the directory.

Below is the program where we create a directory by typing the full path within the line edit element and then click the 'Create Directory' button. Before it creates the directory, the program first checks to see if the directory exists or not. If it doesn't, then the new directory is created.

So the first thing you have to do is create a Qt widget application.

You will have to place 1 line edit element and 1 push button within this widget application.

We label the push button, 'Create Directory', as it functions to create a new directory. We give this element an objectName of 'createDirectoryButton'.

With this, we now go to the heart of our code found in the 'widget.cpp' file.

Within this 'widget.cpp' file, we place the following contents shown below.



We create a variable, of type String, named dirPath. Into this variable, we will store the full path of the directory. The text() function takes the path specified in the line edit element and stores it into this variable.

We then create another variable, dir, which is an object of the QDir class. Within this dir variable, we pass in the full path of the directory.

We then use an if statement to check if the directory exists using the exists() function. If we check to see if it doesn't exist. If it doesn't exist, then we create the directory and output a success statement. Else, we output a statement a statement that the directory already exists.

So the main thing is to create an object of the QDir class and pass into it the full path of the directory you want to create.

Next we use the exists() function to check to see whether that directory exists or not.

And this is how to check if a directory already exists within a given directory in a Qt widget in C++.


Related Resources

How to Write to a File in C++



HTML Comment Box is loading comments...