Jump to content
  • Advertisement
Sign in to follow this  
stelabouras

Checking File Existence in C++

This topic is 5031 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 everybody! Happy New Year! I have got a pretty silly question i must say, but i cannot find the exact solution somewhere.. How i can check a file existence in c++? if for example i have the object : fstream file; and i want my program to check if the file data.dat exists or not in order to extract data from it in the first case what do i have to type? Thanks in advance, Stelabouras

Share this post


Link to post
Share on other sites
Advertisement
If the if_open() method is true after you try to open the file, then the file exists. Otherwise, it does not exist (in the current directory, atleast).


fstream filestr;
filestr.open ("data.dat");
if (filestr.is_open()){
cout << "yay, we found it." << endl;
}
else
cout << "boo, it does not exist :(" << endl;

Share this post


Link to post
Share on other sites
Thanks for your fast answers!

But it seems that there are 2 kind of problems.

Firstly, visage :

filestr.open ("data.dat"); <- visual c++ returns "error C2660: 'open' : function does not take 1 parameters"

And secondly, Trip99 :

which library has the function _access ?

Thank you for your patience,

Stelabouras

Share this post


Link to post
Share on other sites
Whatever api you use the standard answer it to try to open it for reading. If that succeeds then the file exists, if it fails then it doesn't.

The problem with api's that just do the test is that the existance of the file can change between the time you do the test and the time you open it.

Share this post


Link to post
Share on other sites
The reason it asks for a second parameter is that you have an fstream (file stream), and not an ifstream (input file stream). If you wish to hold onto the fstream, though, you can specify ios_base::in as the second parameter. Look here for a reference.

Regards,
jflanglois

Share this post


Link to post
Share on other sites

/*tests if a file exists by opening it then checking the state of it*/
bool fexist(const char *filename)
{
FILE *file = fopen(filename,"r");

if(file) {
fclose(file);
return 1;
}
else {
return 0;
}
}

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!