检查目录是否存在的便携方式[Windows / Linux,C]

时间:2013-08-07 09:47:03

标签: c file directory file-exists

我想检查一个给定的目录是否存在。我知道如何在Windows上执行此操作:

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

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

和Linux:

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

但我需要一种可移植的方式来做这个..有没有办法检查一个目录是否存在,无论我使用什么操作系统?也许是C标准库的方式?

我知道我可以使用预处理程序指令并在不同的操作系统上调用这些函数,但这不是我要求的解决方案。

我最终还是这样,至少现在:

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

int dirExists(const char *path)
{
    struct stat info;

    if(stat( path, &info ) != 0)
        return 0;
    else if(info.st_mode & S_IFDIR)
        return 1;
    else
        return 0;
}

int main(int argc, char **argv)
{
    const char *path = "./TEST/";
    printf("%d\n", dirExists(path));
    return 0;
}

5 个答案:

答案 0 :(得分:80)

stat()适用于Linux。,UNIX和Windows:

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

struct stat info;

if( stat( pathname, &info ) != 0 )
    printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR )  // S_ISDIR() doesn't exist on my windows 
    printf( "%s is a directory\n", pathname );
else
    printf( "%s is no directory\n", pathname );

答案 1 :(得分:3)

使用boost::filesystem,这将为您提供一种可移植的方式来完成这些事情,并为您抽象出所有丑陋的细节。

答案 2 :(得分:1)

您可以使用GTK glib从操作系统中抽象出来。

glib提供了g_dir_open()函数,应该可以解决这个问题。

答案 3 :(得分:1)

在C ++ 17中,您可以使用std::filesystem::is_directory函数(https://en.cppreference.com/w/cpp/filesystem/is_directory)。它接受一个std::filesystem::path对象,该对象可以使用unicode路径构造。

答案 4 :(得分:0)

由于我发现上述批准的答案缺乏明确性,并且操作者提供了他/她将使用的错误解决方案。因此,我希望以下示例对其他人有帮助。该解决方案也或多或少具有便携性。

/******************************************************************************
 * Checks to see if a directory exists. Note: This method only checks the
 * existence of the full path AND if path leaf is a dir.
 *
 * @return  >0 if dir exists AND is a dir,
 *           0 if dir does not exist OR exists but not a dir,
 *          <0 if an error occurred (errno is also set)
 *****************************************************************************/
int dirExists(const char* const path)
{
    struct stat info;

    int statRC = stat( path, &info );
    if( statRC != 0 )
    {
        if (errno == ENOENT)  { return 0; } // something along the path does not exist
        if (errno == ENOTDIR) { return 0; } // something in path prefix is not a dir
        return -1;
    }

    return ( info.st_mode & S_IFDIR ) ? 1 : 0;
}
相关问题