programing

디렉토리가 존재하는지 확인하려면 어떻게 해야 하나요?

prostudy 2022. 6. 18. 09:22
반응형

디렉토리가 존재하는지 확인하려면 어떻게 해야 하나요?

C에 Linux에 디렉토리가 있는지 확인하려면 어떻게 해야 합니까?

를 사용하여 확인할 수 있습니다.ENOENT == errno장애 발생 시:

#include <dirent.h>
#include <errno.h>

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. */
}

다음 코드를 사용하여 폴더가 있는지 확인합니다.Windows 플랫폼과 Linux 플랫폼 모두에서 동작합니다.

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

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

    if (stat(folder, &sb) == 0 && S_ISDIR(sb.st_mode)) {
        printf("YES\n");
    } else {
        printf("NO\n");
    }
}

사용할 수 있습니다.stat()주소를 전달해 주세요.struct stat그 후 멤버를 확인합니다.st_mode가지고 있기 때문에S_IFDIR세트.

#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()");

를 사용할 수도 있습니다.access와 조합하여opendir디렉토리가 존재하는지, 이름이 존재하는지, 디렉토리가 아닌지를 확인합니다.예를 들어 다음과 같습니다.

#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

/* 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); /* d exists and is a directory */
        } else {
            return -2; /* d exists but is not a directory */
        }
    } else {
        return -1;     /* d does not exist */
    }

    return 1;
}

가장 좋은 방법은 아마도 그것을 열려고 시도하는 것입니다.opendir()예를 들어.

파일 시스템리소스를 사용하려고 시도하거나 나중에 시도하거나 하는 것보다 파일 시스템리소스가 존재하지 않기 때문에 발생하는 오류를 처리하는 것이 항상 최선입니다.후자의 접근법에는 명백한 인종 조건이 있다.

man (2) stat에 따르면 st_mode 필드에서 S_ISDIR 매크로를 사용할 수 있습니다.

bool isdir = S_ISDIR(st.st_mode);

참고로 다른 OS에서 소프트웨어를 실행할 수 있다면 Boost 및 Qt4를 사용하여 크로스 플랫폼 지원을 쉽게 할 것을 권장합니다.

언급URL : https://stackoverflow.com/questions/12510874/how-can-i-check-if-a-directory-exists

반응형