How to verify the existence of a folder?

Asked

Viewed 1,478 times

6

To verify the existence of a folder with a C/C++ program, it looks for the directory, if it does not find the specified directory, it will make the decision to create it.

2 answers

3


The best way to do that is by using the opendir, this function works equal to fopen, if you do not find the desired "item" returns NULL.

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <fcntl.h>

int main(int argc, const char **argv){
    int fd = open("/usr/", O_RDONLY | O_DIRECTORY);
    DIR *d1 = fdopendir(fd);

    DIR *d2 = opendir("/etc");
    DIR *d3 = opendir("main.c");

    printf("%i-%i-%i\n", d1, d2, d3);

    if(!d1) puts("d1 não é um diretório ou não existe.");
    else mkdir("/usr/");

    if(!d2) puts("d2 não é um diretório ou não existe.");
    else mkdir("/usr/");

    if(!d3) puts("d3 não é um diretório ou não existe.");

    close(d1);
    close(d2);
    close(fd);

    return 0;
}

Directories can be opened using function return open, or directly (this depends on the preference or need).


Already the Windows owns the GetFileAttributes

#include <windows.h>

BOOL DirectoryExists(LPCTSTR path)
{
  DWORD dwAttrib = GetFileAttributes(path);

  return (dwAttrib != INVALID_FILE_ATTRIBUTES && 
         (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}

int main(int argc, const char **argv){
    if(DirectoryExists("c:/Windows"))
        puts("O diretório existe!");
    else
        mkdir("c:/Windows");

    return 0;
}
  • "opendir" is neither standard of C nor C++, and does not exist in Windows, Moreover, according to the question asked the best solution is to simply create the directory; if the directory already exists the attempt to create it again will return error.

  • Fixed to check on Windows too. The mkdir can solve this problem, but in case problems appear that it is not feasible to use it, it is good to also know other means.

  • it is generally not advisable to "test and then use", because in the time interval between "test" and "use", the test result may have lost its validity...this is an "anti-pattern" known as TOCTOU: https://en.wikipedia.org/wiki/Time_check_to_time_of_use

  • really this can consume extra time, but in this case, it is just a teaching material, the focus is to learn how to use the language’s functionalities, make a performance analysis and response time is already something more professional. I don’t think that fits in with this challenge.

0

You can call right the mkdir, if the directory exists it will return -1, if the directory does not exist it will be created and returns 0

A detail I forgot to mention regarding the direct use of mkdir, is the performace.... If you need to check many folders and if you have not been creating advise the use of the second code

Code to check if it exists and create if it does not exist:

#include <sys/stat.h>
#include <stdio.h>

int main(int argc, const char **argv){
    int f = mkdir("C:/Pasta");

    if (f == -1)
       puts("Diretório já existe.");
    else
       puts("Diretório criado.");

    return 0;
}

Code automate folder creation:

#include <sys/stat.h>
#include <stdio.h>

int main(int argc, const char **argv){
    int tam = 2;
    char *pastas[tam];
    pastas[0] = "pasta1";
    pastas[1] = "pasta2";

    for (int i = 0, i < tam, i++)
        mkdir(pastas[i]);

    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.