• C

Checking if a file exists

How would I check to see if a given file exists? Not necessarily to open it or close it or anything, just to see if it exists.
SonicX_BlueBlurAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sunnycoderCommented:
pedantically it is not possible to chek in absolute terms ....

use fstat() or access() to determine if you can access a file or a file exists
sunnycoderCommented:
from fstat man page
You do not need any access rights to the file to get this information but you need
       search rights to all directories named in the path leading to the file.
thus if you do not have search right on the path, the call will fail even if file exists ...

from access man page
 The tests depend on the permissions of the directories occurring in the path to the file, as given in pathname, and on the permissions of direc­tories and files referred to by symbolic links encountered on the way.

int i;
i = access ( "filename", F_OK );

if ( i == 0 )
          printf ( "file exists\n" );

infact stat will be better than fstat as you do not have to open a file
struct stat buf;
i = stat ( "filename", &buf );
if ( i == 0 )
          printf ( "file exists\n" );
SonicX_BlueBlurAuthor Commented:
Well, that's a start...but I'm not really the most advanced C coder there is, so I have no clue how to actually {use, determine if the file exists using} fstat or access.

Also, I'm adding 25 points to also know how to copy a file from, well, Point D: to point C:. :P
Basically, we're talking, checking if a file is there, and putting it there if it's not.
Defend Against the Q2 Top Security Threats

Were you aware that overall malware worldwide was down a surprising 42% from Q1'18? Every quarter, the WatchGuard Threat Lab releases an Internet Security Report that analyzes the top threat trends impacting companies worldwide. Learn more by viewing our on-demand webinar today!

sunnycoderCommented:
>so I have no clue how to actually {use, determine if the file exists using} fstat or access.
I just posted relevant code snippets

>but I'm not really the most advanced C coder
Is this your homework ?
SonicX_BlueBlurAuthor Commented:
First remark: Yeah, I'd posted after you did, without seeing your post.

Second remark: At my college (NBCC Miramichi), we don't even touch C before the last week of the first semester. The only reason I'm using C at all is that I need to check for MSVBVM60.DLL on new computers so that I can get a VB6 program running on them. So, no, this ain't homework.
sunnycoderCommented:
>know how to copy a file from, well, Point D: to point C:.
system ( "copy source destination" );

basically the string in the " " is the shell command which you would give on the command prompt to copy the file

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SonicX_BlueBlurAuthor Commented:
All right. Well, let's see what we can do with this. I'm just gonna cash out this question now and ask another if it doesn't work.
mdhmiCommented:
Here is a real simple portable way to see if a file exists.  I coded this to be portable and extremely easy to read.

#include <stdio.h>

int FileExist (char * fileName);
int main(void)   {
   int ret=(0);
   ret = FileExist ("/tmp/mytestfile");
   if (ret == (0) )   {
      printf ("File exists\n");
   } else   {
      printf ("File does not exist\n");
   }
   return (0);
}

int FileExist (char * fileName)
{
   FILE * infile;
   int ret = (0);
   infile = fopen (fileName, "r");
   if (infile == NULL)   {
      ret = (1);
   }
   else   {
      ret = (0);
   }
   close (infile);
   return (ret);
}

Regards,

Mark
gafdaCommented:
If your're working with 'C':

#include <stdio.h>

int main()
{
      FILE *f;

      if((f = fopen("file.txt","rt")) == NULL)
      {
            fprintf("File does not exist on specified directory.");
            exit(123);
      }

         return 0;
}
shwetaabhishekCommented:
if the file does not exist then i want to create it a new file
how to do that
sunnycoderCommented:
shwetaabhishek,

Please ask your question in a spearate thread. Look for "ask a question" link in the left panel

sunnycoder
themuppeteerCommented:
small correction to the function:

int FileExist (char * fileName)
{
   FILE * infile;
   int ret = (0);
   infile = fopen (fileName, "r");
   if (infile == NULL)   {
      close (infile);// if you don't close, you get in trouble..
      ret = (1);
   }
   else   {
      close (infile); // if you don't close, you get in trouble..
      ret = (0);
   }
   close (infile);
   return (ret);
}


br,
themuppeteer
themuppeteerCommented:
Sorry, I was wrong, the function is correct indeed. Guess I was sleeping..
But I do get in trouble when I use it a quickely in a loop. For some reason, infile starts switching from NULL to not NULL. I coulnd't believe this, so I placed a printf under infile = fopen(..); and really, infile goes from NULL to not null, flickering like a christmis tree . Anyone knows why ?
themuppeteerCommented:
the stat thing worked. Thanks guys!

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

int fileExists (char * fileName)
{
   struct stat buf;
   int i = stat ( fileName, &buf );
      if ( i == 0 )
      {
       return 1;
      }
      return 0;
       
}
TeJoRoBoCommented:
> Comment from themuppeteer
> Sorry, I was wrong, the function is correct indeed. Guess I was sleeping..
>But I do get in trouble when I use it a quickely in a loop. For some reason, infile starts switching from NULL to not NULL. I >coulnd't believe this, so I placed a printf under infile = fopen(..); and really, infile goes from NULL to not null, flickering >like a christmis tree . Anyone knows why?

I'm not sure but it could be because you close the file whether you've successfully opened it or not.  You should only close a file you've successfully opened.  Otherwise the results are unpredictable.

Terry
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.