How to check if a file exists in C?

Started by
7 comments, last by dalleboy 19 years, 6 months ago
Hello, In PHP we have the function "file_exists" that returns true in success, e.g.:

<?php
if(file_exists("files/model.md2")) {
    printf("File found!");
}
?>

And what about C? Which function has a feature like this? Thanks.
Alfred Reinold Baudisch[Game Development Student] [MAC lover] [Ruby, Ruby on Rails and PHP developer] [Twitter]
Advertisement
Just try opening it for reading. If it suceeds the file exists.

bool file_exists(const char * filename){    if (FILE * file = fopen(filename, "r"))    {        fclose(file);        return true;    }    return false;}


Alan

/edit: Ahem. Nothing to see here, move along. Thanks Oxyd

[Edited by - AlanKemp on August 27, 2004 1:42:36 PM]
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour

FILE *istream;
if ( (istream = fopen ( "file.txt", "r" ) ) == NULL )
{
printf ( "file non-existant!\n" );
}
else
{
printf ( "file exists!\n" );
fclose ( istream );
}
[\code]
bool file_exists(const char * filename){    if (FILE * file = fopen(filename, "r")) //I'm sure, you meant for READING =)    {        fclose(file);        return true;    }    return false;}
Thanks guys for the replies!
Alfred Reinold Baudisch[Game Development Student] [MAC lover] [Ruby, Ruby on Rails and PHP developer] [Twitter]
For the C++ in you...
std::fstream foo;foo.open("bar");if(foo.is_open() == true)     std::cout << "Exist";else      std::cout << "Doesn't Exist";


~~~~~Screaming Statue Software. | OpenGL FontLibWhy does Data talk to the computer? Surely he's Wi-Fi enabled... - phaseburn
Oh, I was so lazy that I couldn't access google [flaming]
And I googled now and found this function:´

#include<sys/stat.h>int file_exists (char * fileName){   struct stat buf;   int i = stat ( fileName, &buf );     /* File found */     if ( i == 0 )     {       return 1;     }     return 0;       }


[google]

Thanks again for your replies.
Alfred Reinold Baudisch[Game Development Student] [MAC lover] [Ruby, Ruby on Rails and PHP developer] [Twitter]
"open" and "stat" are a bit of an overkill.
"access" is a much lighter function..
Quote:Original post by Anonymous Poster
"open" and "stat" are a bit of an overkill.
"access" is a much lighter function..

Add one more vote on 'access'.
Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]

This topic is closed to new replies.

Advertisement