Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking directory existence 2

Status
Not open for further replies.

KyoAD

Technical User
Aug 5, 2002
106
SG
I have been using the fopen to check for the existence of a file. However, how can i check if a directory exists? For example, to check the existence of c:\test with no files inside?
 
No portable library functions for this task.
See for Windows:
Code:
#include <io.h>
bool isLive(const char* name)
{
  return name && _access(name,0)==0;
}

#include <windows.h>
bool isDir(const char* dir)
{
  HANDLE h;
  WIN32_FIND_DATA info;
  bool res = false;
  if (dir 
  && (h=FindFirstFile(dir,&info)) != INVALID_HANDLE_VALUE
  && (info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY))
  {
    res = true;
    FindClose(h);
  }
  return res;
}
The isLive() returns true/false for dir or file (it can't recognize is it a dir or a file).
The isDir() returns true for directories only, but it has some defect: it can't recognize a root directory (it returns false for C:\, for example), because of a root directory has not directory attribute on Windows (alas;)...
 
Not sure if this still works.
In old DOS/FAT, every directory had a pseudo file called NUL. Whether this still exists in say XP/NTFS is another matter.

So you would do
Code:
FILE *fp;
if ( (fp=fopen("c:\\test\\nul","r")) != NULL ) {
  fclose(fp);
  // directory exists
}

--
 
On POSIX systems:
Code:
#include <sys/types.h>
#include <dirent.h>

DIR* dp;

if ( ( dp = opendir( "/usr/local/share" ) != NULL )
{
    closedir( dp );
    /* It's there */
}
else
{
    /* It ain't there */
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top