Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) FileExists

 

FileExists is a file I/O code snippet to checks if a file exists.

 

 

 

 

 

Boost Boost FileExists

 

Uses the Boost.Filesystem library.

 

#include <boost/filesystem.hpp>

///FileExists checks if a certain file exists
///From http://www.richelbilderbeek.nl/CppFileExists.htm
bool FileExists(const std::string& filename)
{
  return boost::filesystem::exists(filename) ;
}

 

 

 

 

 

Qt Qt FileExists

 

///FileExists checks if a certain file exists
///From http://www.richelbilderbeek.nl/CppFileExists.htm
bool FileExists(const std::string& filename)
{
  return QFile::exists(filename.c_str());
}

 

 

 

 

 

STL STL FileExists

 

#include <string>
#include <fstream>

///FileExists checks if a certain file exists
///From http://www.richelbilderbeek.nl/CppFileExists.htm
bool FileExists(const std::string& filename)
{
  std::fstream f;
  f.open(filename.c_str(),std::ios::in);
  return f.is_open();
}

 

 

 

 

 

VCL VCL FileExists

 

The VCL library also contains a FileExists function.

 

 

 

 

 

Qt and STL FileExists on Qt resources

 

The STL version of FileExists will not find Qt resources, as shown in the example below:

 

 

#include <cassert>
#include <string>
#include <fstream>

#include <QFile>

///FileExists checks if a certain file exists
///From http://www.richelbilderbeek.nl/CppFileExists.htm
bool FileExistsStl(const std::string& filename)
{
  std::fstream f;
  f.open(filename.c_str(),std::ios::in);
  return f.is_open();
}

///FileExists checks if a certain file exists
///From http://www.richelbilderbeek.nl/CppFileExists.htm
bool FileExistsQt(const std::string& filename)
{
  return QFile::exists(filename.c_str());
}

int main(int argc, char* argv[])
{
  //The program filename exists
  const std::string filename = argv[0];
  assert(FileExistsStl(filename));
  assert(FileExistsQt(filename));

  const std::string resource_filename = ":/images/R.png";
  assert(!FileExistsStl(resource_filename)
    && "Qt resources are not detected by STL");
  assert(FileExistsQt(resource_filename)
    && "Qt resources are detected by Qt");
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict