Jump to content
  • Advertisement
Sign in to follow this  
Maquiavel

How to check if a file exists in C?

This topic is 5114 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

FILE *istream;
if ( (istream = fopen ( "file.txt", "r" ) ) == NULL )
{
printf ( "file non-existant!\n" );
}
else
{
printf ( "file exists!\n" );
fclose ( istream );
}
[\code]

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
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";


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
"open" and "stat" are a bit of an overkill.
"access" is a much lighter function..

Share this post


Link to post
Share on other sites
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'.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!