Check if a file exists using C++There are many ways to check if a file exists in C++, however there are some ways which are better. Many people just say you should try to open it and if that fails, it doesn't exist. That method is slightly flawed because in some cases you may just not have permission to read the contents of the file, which is why the open is failing. A better way to check if a file exists is to use the stat() function. This function returns the file attributes of a file and therefore doesn't ever attempt to open it. The following code is an example of how to use stat to check if a file exists. Note the comments which show you where this function could be extended if more details are required.
#include <sys/stat.h>
bool FileExists(string strFilename) { struct stat stFileInfo; bool blnReturn; int intStat; // Attempt to get the file attributes intStat = stat(strFilename.c_str(),&stFileInfo); if(intStat == 0) { // We were able to get the file attributes // so the file obviously exists. blnReturn = true; } else { // We were not able to get the file attributes. // This may mean that we don't have permission to // access the folder which contains this file. If you // need to do that level of checking, lookup the // return values of stat which will give you // more details on why stat failed. blnReturn = false; } return(blnReturn); } Using stat is also portable between operating systems and therefore you should be able to use this same code on Linux, Windows, Unix, Solaris, etc. The only thing that may differ between operating systems and compilers is the name of the include file (even though it shouldn't change). Author: DPAK Created: Dec 1 2005 Categories: C++ TechByte #103 Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.
Add a comment about this TechByteIf you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED. Other TechBytes: |
|

