Jak mogę sprawdzić, czy katalog istnieje?

Jak mogę sprawdzić, czy katalog istnieje na Linuksie w C?

Author: alk, 2012-09-20

7 answers

Możesz użyć opendir() i sprawdzić czy ENOENT == errno po awarii:

DIR* dir = opendir("mydir");
if (dir)
{
    /* Directory exists. */
    closedir(dir);
}
else if (ENOENT == errno)
{
    /* Directory does not exist. */
}
else
{
    /* opendir() failed for some other reason. */
}
 53
Author: hmjd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-20 10:38:31

Użyj poniższego kodu, aby sprawdzić, czy folder istnieje. Działa na platformach Windows i Linux.

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

int main(int argc, char* argv[])
{
    const char* folderr;
    //folderr = "C:\\Users\\SaMaN\\Desktop\\Ppln";
    folderr = "/tmp";
    struct stat sb;

    if (stat(folderr, &sb) == 0 && S_ISDIR(sb.st_mode))
    {
        printf("YES\n");
    }
    else
    {
        printf("NO\n");
    }
}
 30
Author: Saman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-03 03:19:21

Możesz użyć stat() i podać mu adres struct stat, a następnie sprawdzić jego element st_mode, Czy S_IFDIR jest ustawiony.

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

...

char d[] = "mydir";

struct stat s = {0};

if (!stat(d, &s))
  printf("'%s' is %sa directory.\n", d, (s.st_mode & S_IFDIR)  : "" ? "not ");
  // (s.st_mode & S_IFDIR) can be replaced with S_ISDIR(s.st_mode)
else
  perror("stat()");
 14
Author: alk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-30 09:22:00

Najlepszym sposobem jest prawdopodobnie próba otwarcia go, używając na przykład tylko opendir().

Zauważ, że zawsze najlepiej jest spróbować użyć zasobu systemu plików i zająć się wszelkimi występującymi błędami, ponieważ nie istnieje, a nie tylko sprawdzać, a następnie próbować. W tym drugim podejściu istnieje oczywisty stan rasy.

 8
Author: unwind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-20 10:38:23

Zgodnie z man(2)stat możesz użyć makra S_ISDIR w polu st_mode:

bool isdir = S_ISDIR(st.st_mode);

Na marginesie, zalecałbym użycie Boost i / lub Qt4, aby ułatwić obsługę międzyplatformową, jeśli twoje oprogramowanie może być opłacalne w innych systemach operacyjnych.

 4
Author: TheFriendlyDragon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-15 22:45:24

Możesz również użyć access w połączeniu z opendir, aby określić, czy katalog istnieje, a jeśli nazwa istnieje, ale nie jest katalogiem. Na przykład:

/* test that dir exists (1 success, -1 does not exist, -2 not dir) */
int
xis_dir (const char *d)
{
    DIR *dirptr;

    if (access ( d, F_OK ) != -1 ) {
        // file exists
        if ((dirptr = opendir (d)) != NULL) {
            closedir (dirptr);
        } else {
            return -2; /* d exists, but not dir */
        }
    } else {
        return -1;     /* d does not exist */
    }

    return 1;
}
 2
Author: David C. Rankin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-12 08:46:08

Inne dwa sposoby, może mniej poprawne jest użycie. Pierwsza, używająca tylko standardowych bibliotek i tylko dla plików:

FILE *f;
f = fopen("file", "r")
if(!f)
   printf("there is no file there");
Ten może działać na wszystkich systemach operacyjnych.

Lub inny również dla dirs, używając wywołania systemowego z system (). Jest najgorszą opcją, ale daje inny sposób. Dla kogoś, kto może się przydać.

 -5
Author: ferbuntu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-20 11:47:55