Sign in to follow this  

C++ check to see if a file exists

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

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