Solved

Checking if a file exists

Posted on 2003-11-21
15
56,406 Views
Last Modified: 2011-08-18
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.
0
Comment
Question by:SonicX_BlueBlur
  • 5
  • 3
  • 3
  • +4
15 Comments
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9801516
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
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9801539
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" );
0
 

Author Comment

by:SonicX_BlueBlur
ID: 9801555
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.
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 9801558
>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 ?
0
 

Author Comment

by:SonicX_BlueBlur
ID: 9801617
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.
0
 
LVL 45

Accepted Solution

by:
sunnycoder earned 75 total points
ID: 9801621
>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
0
 

Author Comment

by:SonicX_BlueBlur
ID: 9801678
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.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 1

Expert Comment

by:mdhmi
ID: 10241647
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
0
 

Expert Comment

by:gafda
ID: 10640706
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;
}
0
 

Expert Comment

by:shwetaabhishek
ID: 10820659
if the file does not exist then i want to create it a new file
how to do that
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 10820763
shwetaabhishek,

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

sunnycoder
0
 
LVL 2

Expert Comment

by:themuppeteer
ID: 11414100
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
0
 
LVL 2

Expert Comment

by:themuppeteer
ID: 11426239
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 ?
0
 
LVL 2

Expert Comment

by:themuppeteer
ID: 11426603
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;
       
}
0
 

Expert Comment

by:TeJoRoBo
ID: 14621266
> 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
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now