Solved

Checking if a file exists

Posted on 2003-11-21
15
56,431 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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
 
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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
logging Access violation 6 19
mixing C++ and C code elegantly 10 158
Problem in finding output of a program 11 106
Using ANSI C how to Read a .csv file 10 95
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

860 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