How to check the existence of a folder?

6

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

    
asked by anonymous 14.12.2016 / 00:54

2 answers

3

The best way to do this is to use opendir , this function works equal to fopen , if you do not find the desired "item" return 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;
}

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

Windows has 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;
}
    
15.12.2016 / 20:06
0

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

A detail that I forgot to mention in relation to the direct use of mkdir , is the performace .... If you need to check many folders and if you do not go creating I advise you to use 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;
}
    
14.12.2016 / 01:26