Start New Discussion within our Software Development Community

Code written and tested using the Borland C++ compiler.

Code uses access() to determine if an input string exists either as a directory name or as a file name. If access() fails, the string is neither a file or directory and the function terminates. If it does exist, the name is used as input to opendir() to determine if a directory stream can be opened for that name. If it can, the string is a directory name. Otherwise, it's a file.

// ISDIR: Returns 1 if the string is a directory,
//                0 if it's a file,
//               -1 otherwise
#include <dirent.h>
#include <io.h>
int isdir(char *in_string);
int isdir(char *in_string)
{
DIR *dir; // <dirent.h>

// Access function 0 determines if an object exits, whether file or directory
if (access(in_string,0) != 0) // <io.h>
   return -1; // Function failed. No clean up, just return the "fail" flag.

// The object, whatever it is, exists

// Try to open the object as a directory stream
dir = opendir(in_string);
if (dir != NULL) 
   {
   // Object successfully opened as a directory stream
   // Close the open directory stream and return the "is a directory" flag
   closedir(dir);
   return 1;
   }

// All that's left is for it to be is a file. Return the "is a file" flag
return 0;
}