Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable way to check if directory exists [Windows/Linux, C]

I would like to check if a given directory exists. I know how to do this on Windows:

BOOL DirectoryExists(LPCTSTR szPath) {   DWORD dwAttrib = GetFileAttributes(szPath);    return (dwAttrib != INVALID_FILE_ATTRIBUTES &&           (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } 

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

But I need a portable way of doing this .. Is there any way to check if a directory exists no matter what OS Im using? Maybe C standard library way?

I know that I can use preprocessors directives and call those functions on different OSes but thats not the solution Im asking for.

I END UP WITH THIS, AT LEAST FOR NOW:

#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; } 
like image 952
ivy Avatar asked Aug 07 '13 09:08

ivy


People also ask

How can I check if a folder is present?

$Folder = 'C:\Windows' "Test to see if folder [$Folder] exists" if (Test-Path -Path $Folder) { "Path exists!" } else { "Path doesn't exist." } This is similar to the -d $filepath operator for IF statements in Bash. True is returned if $filepath exists, otherwise False is returned.


1 Answers

stat() works on Linux., UNIX and Windows as well:

#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 ); 
like image 62
Ingo Leonhardt Avatar answered Sep 21 '22 08:09

Ingo Leonhardt