Determining Filesystem Object Information
From CodeCodex
Determining whether something is a file, a directory, or something else.
[edit] C/C++
(C code will need to include <stdbool.h>.)
file_exists returns true if Pathname references a filesystem object which exists and is a regular file, false otherwise (doesn’t exist or isn’t a regular file). It also returns false if an error was encountered. A symlink to a file is treated the same as a file.
bool file_exists
(
const char * Pathname
)
/* is there a regular file by the name of Pathname. */
{
bool Exists;
struct stat Info;
if (stat(Pathname, &Info) == 0)
{
Exists = S_ISREG(Info.st_mode);
}
else
{
Exists = false;
} /*if*/
return
Exists;
} /*file_exists*/
directory_exists similarly checks if Pathname points to something which exists and is a directory. It also has the option of whether to treat a symlink to a directory as a directory or not.
bool directory_exists
(
const char * Pathname,
bool FollowSymlink
/* true to return true if Pathname is a symlink to a directory,
false to return false for a symlink */
)
/* is there a directory by the name of Pathname. */
{
bool Exists;
struct stat Info;
if
(
(FollowSymlink ?
stat(Pathname, &Info)
:
lstat(Pathname, &Info)
)
==
0
)
{
Exists = S_ISDIR(Info.st_mode);
}
else
{
Exists = false;
} /*if*/
return
Exists;
} /*directory_exists*/
See Checking file existence for simple object existence checks.

