Sign in to follow this  

How to check if a file exists in C?

This topic is 4834 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
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

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

This topic is 4834 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this