1753388 Members
7219 Online
108792 Solutions
New Discussion юеВ

Program in C

 
SOLVED
Go to solution
Henry Chua
Super Advisor

Program in C

Hi Guys,

Is there anyway I can write a program in C to check whether a file exist in a path?
regards
Henry
9 REPLIES 9
Biswajit Tripathy
Honored Contributor

Re: Program in C

# man 2 stat

- Biswajit
:-)
Amit Agarwal_1
Trusted Contributor
Solution

Re: Program in C

Yes, as Biswajit said "stat()" is the answer. Here is a small program for the same.
================
#include
#include

int main() {

struct stat bstat;

if (stat("filename", &bstat) < 0) {
fprintf(stderr, "file does not exist\n");
} else {
fprintf(stderr, "file does exist\n");
}
}
===========

-Amit
Muthukumar_5
Honored Contributor

Re: Program in C

If you want to check file availablity with c coding then, you can simply use fopen() also as,

#include

main()
{

FILE *fp;
fp=fopen("filename1","r");
if (!fp){
printf ("Filename filename1 is not existing\n");
} else {
printf ("Filename filename1 is existing\n");
}
}

Change filename1 with full path as like "/tmp/test/filenam1" also in fopen().

hth.
Easy to suggest when don't know about the problem!
dirk dierickx
Honored Contributor

Re: Program in C

if you want to write this to incorporate it into a script, you should not waste your time doing so. unix has the 'test' command (man test) which has lots of options for checking files.
Antoniov.
Honored Contributor

Re: Program in C

Hi Henry,
I used same routine of Muthukumar with fopen function. It works with any c and any platform.

Antonio Vigliotti.
Antonio Maria Vigliotti
A. Clay Stephenson
Acclaimed Contributor

Re: Program in C

The stat() system call is a much better choice than fopen. First, it's cheaper in terms of system resources but more importantly, fopen() (or open()) could very easily fail even if the file actually exists. How? You specify a mode (e.g. "r") when using fopen(), if the file exists but has only write or execute bits set, your fopen() will fail. Use stat(); if it returns a zero result then the operation was okay; you then use the mode field to determine if the file is a regular file and has the desired permission bits sets. If stat returns a non-zero result then you look at errno and determine why it failed.
If it ain't broke, I can fix that.
D Block 2
Respected Contributor

Re: Program in C

I agree w/ Clay.. use the stat(2) system call.. you can also use the fopen(3), if you like.

Golf is a Good Walk Spoiled, Mark Twain.
Antoniov.
Honored Contributor

Re: Program in C

Clay,
thank you for stat information. I read the help on stat function. I think I'll use that next time.

Antonio Vigliotti
Antonio Maria Vigliotti
Stephen Keane
Honored Contributor

Re: Program in C

Don't forget the access(2) system call