Return to Snippet

Revision: 52039
at October 11, 2011 23:04 by StraightforAward


Initial Code
#include <stdio.h>    //FILE, fopen(), fclose()
#include <sys/stat.h> //stat, stat()
#include <string>     //string
#include <fstream>    //fstream 
#include <iostream>   //cout
 
using namespace std;
 
bool OpenCFileExists(const char* filename)
{
    FILE* fp = NULL;
 
    //this will fail if more capabilities to read the 
    //contents of the file is required (e.g. \private\...)
    fp = fopen(filename, "r");
 
    if(fp != NULL)
      {
        fclose(fp);
        return true;
      }
    fclose(fp);
 
    return false;
}
 
bool OpenCppFileExists(const string& filename)
{
  fstream fin;
 
  //this will fail if more capabilities to read the 
  //contents of the file is required (e.g. \private\...)
  fin.open(filename.c_str(), ios::in);
 
  if(fin.is_open())
    {
    fin.close();
    return true;
    }
  fin.close();
 
  return false;
}
 
bool FileExists(const char* filename) 
{
  struct stat info;
  int ret = -1;
 
  //get the file attributes
  ret = stat(filename, &info);
  if(ret == 0) 
    {
    //stat() is able to get the file attributes,
    //so the file obviously exists
    return true;
    } 
  else 
    {
    //stat() is not able to get the file attributes,
    //so the file obviously does not exist or
    //more capabilities is required
    return false;
    }
}
bool FileExists(const string& filename) 
{
  return FileExists(filename.c_str());     
}
 
//the simple test program for above functions 
int main()
{
  string filename;
 
  cout << "Enter the filename (empty line quit):" << endl;
  cout << ">";
 
  while(getline(cin, filename)) 
    {
    string result;
 
    if(filename.size() == 0) 
      break;
 
    OpenCFileExists(filename.c_str()) ?  
      result = " found!" : result = " not found!";
    cout << "OpenCFileExists: " << filename << result << endl;
 
    OpenCppFileExists(filename) ?  result = " found!" : result = " not found!";
    cout << "OpenCppFileExists: " << filename << result << endl;
 
    FileExists(filename) ?  result = " found!" : result = " not found!";
    cout << "FileExists: " << filename << result << endl;
 
    cout << ">";
    }
 
 
  return 0;
 
}

Initial URL
http://www.developer.nokia.com/Community/Wiki/CS001101_-_Checking_if_a_file_exists_in_C_and_C%2B%2B

Initial Description

                                

Initial Title
Check if a file exists

Initial Tags
file, path

Initial Language
C++