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!

Performing file test operations in C

Status
Not open for further replies.

akn846

Technical User
Oct 16, 2001
51
GB
I need to write a C program which will test to see whether or not a file exists within a given directory or not.

I know how to do this in Unix shell script (Korn) but I would appreciate it if someone could tell me how I could do something similar in C?

Thanks

Andy
 
#include <iostream.h>
#include <windows.h>
void main()
{
WIN32_FIND_DATA file;
HANDLE hFile;
if (( hFile = FindFirstFile( &quot;file_path&quot;,&file ))
== INVALID_HANDLE_VALUE )
{
cout<<&quot;Can't found this file in that directory !&quot;<<endl;
exit(0);
}
FindClose( hFile );
}

replace 'file_path' with the convenient file directory.
 
Can try something like this.

#include <sys/types.h>
#include <sys/stat.h>

int FileExists(char *filename)
{
struct stat buf;

if( stat(filename, &buf) )
{
printf(&quot;File Does Not Exist!&quot;);
return -1;
}

return 0; /*File Exists*/
}

see man pages for stat for details
 
Since stat() can fail for various reasons and will
return a &quot;-1&quot; on failure you probably want to do...

...
if( (stat(filename, &buf)) < 0 )
{
if( errno == ENOENT)
printf(&quot;File Does Not Exist!&quot;);
else
printf(&quot;Error getting file stat&quot;);
return -1;
}
...

Of course, it's probably better to use &quot;perror()&quot; to get the exact
system error message. In any case, the error codes would be listed
in the man pages...


ERRORS
EBADF filedes is bad.

ENOENT A component of the path file_name does not exist,
or the path is an empty string.

ENOTDIR
A component of the path is not a directory.

ELOOP Too many symbolic links encountered while travers­
ing the path.

EFAULT Bad address.

EACCES Permission denied.

ENOMEM Out of memory (i.e. kernel memory).

ENAMETOOLONG
File name too long.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top