Author Topic: Checking if a file exist  (Read 4551 times)

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
Checking if a file exist
« on: February 06, 2006, 09:36:42 AM »
A potential cause of error is when you try to read a file and the file does not exist.  Obviously this can be avoided if you check for the existence of the file before doing any I/O operation.

One implementation involves creating a a function FileExists that returns a boolean value true if the file is found and false if otherwise.

Code: [Select]

bool fileExists(string filename)
{
   ifstream fin;
   bool result;
   
   fin.open(filename.c_str(), ios::in);
   if( fin.is_open() )
   {
      result = true;
   } else {
      result = false;
   }
   
   fin.close();
   return result;
}

Analyze. Design. Develop. Debug. Deploy. Maintain.

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
Application of file checker
« Reply #1 on: February 06, 2006, 09:42:25 AM »
Write a program that will search a a file of numbers of type int and write the largest and smallest number to the screen.  The file contains nothing but numbers of type int separated by blanks or line breaks.


SOLUTION

Code: [Select]

#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>

using namespace std;

bool fileExists(string filename);
void findHighestLowest();

int main()
{
   cout << "** A Program to find highest and lowest numbers in a list **\n\n";
   
   findHighestLowest();
   
   system("PAUSE");
   return 0;
}

bool fileExists(string filename)
{
   ifstream fin;
   bool result;
   
   fin.open(filename.c_str(), ios::in);
   if( fin.is_open() )
   {
      result = true;
   } else {
      result = false;
   }
   
   fin.close();
   return result;
}

void findHighestLowest()
{
     ifstream fin;
     double next, highest=0, lowest=9999;
     string filename = "integers.txt";
     
     //check if file exist
     if ( ! fileExists(filename) )
     {
         cout << "Data file not found!  Please check that the data file exists."
                     << endl;
         cout << "Program terminated." << endl;
         system("PAUSE");
         exit(1);
     }
     
     fin.open("integers.txt");
     fin >> next;
     while(! fin.eof() )
     {
         cout << next << endl;
         
         if (next > highest) highest = next;
         if (next < lowest) lowest = next;
         fin >> next;
     }
     fin.close();
     
     cout << "Highest = " << highest << endl;
     cout << "Lowest = " << lowest << endl;    
}

Analyze. Design. Develop. Debug. Deploy. Maintain.