• 13
• 16
• 27
• 9
• 9

C++ check to see if a file exists

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

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 on other sites
std::ifstream::gtell() ?

Platform-specific fstat() functions ?

Portable C++ boost::filesystem::file_size() ?

Share on other sites
Quote:
 Original post by moucardI'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.