Tuesday, October 13, 2009

C code to check for the existance of a file

Recently I came across this question to check if a file exists in a given directory. The question looks pretty simple, but most of those guys just out of college will have trouble doing this, its for them that I write this down. Actually, you are supposed to know all this. But nothing happens as expected during college. So lets look at it at least now. There are many ways to do the same.
You can do a fopen and if it fails then you can probably assume that the file doesn't exist. The standard practice in the software industry is to use a stat() function.

int intStat;
struct stat stFileInfo;
intStat = stat(filename,&stFileInfo);
printf("File already exists!!!\n ");
printf("File doesnt exist\n ");

So,this is how you will check whether a file exists or not with the stat function. From now on use this method rather than checking whether fopen fails
Thanking you,