Jump to content
  • Advertisement
Sign in to follow this  
moucard

C++ check to see if a file exists

This topic is 4931 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 again. I'd like to get opinions on what is the best way to check if a file exists in C++. I need to see if the file exists and if so append stuff on it. If it doesn't exist I should create it anew. My problem is if I open the file at the end with:
datafile.open(filename, ios::in | ios::out | ios::ate);
How can I check if it's an empty file? The first read I'll make will be EOF?

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by moucard
I'd like to get opinions on what is the best way to check if a file exists in C++.
Open it for input only. If it fails, the file does not exist:
ifstream fin(filename);
if(!fin.fail())
{
fin.close();
}
ofstream fout(filename);
fout.seekg(0, ios::end);
// ready to append
Of course, this is redundant. If you're going to create the file when it doesn't exist, then just open it for output and seek to the end.

Share this post


Link to post
Share on other sites
If your windows only we get great millage out of ::PathFileExists( LPCTSTR ), there is a whole wack of usefull file methods for windows, search under ::Path****

Cheers
Chris

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!