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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search if a file exists, check if a directory exists

Status
Not open for further replies.

labnotes

Technical User
Sep 1, 2003
33
CA
Is there a function in C that will check if a directory exists?
To check if a file exists do I have to open it or can I just do a find?
 
To discover if a file exists using standard ANSI C you would have to attempt to open a file without creating it and see if an error occurs. Other OS specific APIs are available that do not require opening the file.

Since you posted this question in this forum I will assume you are running on Windows and have access to the Win32 API. See the documentation for FindFirstFile(…)


-pete
 
I would prefer the GetFileAttributes API.

Code:
#include <windows.h>

char  FileOrDirName[MAX_PATH] = &quot;X:\\Whatever\\you\\want&quot;;

DWORD dwAttr = GetFileAttributes ( FileOrDirName );
if ( dwAttr == 0xffffffff )
   { // failure, reason could be not present, access denied
     //          or something else
     DWORD dwReason = GetLastError ( );
     ...  } else
   { if ( dwAttr & FILE_ATTRIBUTE_DIRECTORY )
        { // it is a directory
          ... } else
        { // it is a file
          ... } }

Marcel
 
There is another easy way to see if a file exists:
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
....
/* Check for existence */
if( (_access( &quot;ACCESS.C&quot;, 0 )) != -1 )
{
printf( &quot;File ACCESS.C exists\n&quot; );
}
...
-obislavu-

 
I agree with the GetFileAttributes and it is what I have used in the past (does both files and directories)... you could also use CFileFind. For directories with CFileFind, you may not have as much luck and may need to figure out another way.

The brainless approach is to switch directories and then restore back to the old one.

getcwd
chdir
chdir <back to old one>

Return value from first chdir will be zero if it exists.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top