// Zig Herzog
// Oct. 2007
// Reading data from file , text chapter 4.2
// Create data input file using any text editor
// Content of data input file : one integer number per line, any number of lines
//              In general : There are no limits on the types of data in a file
//                           but your program has to match the content of the file

#include <iostream> 
#include <fstream>   // Needed for interfacing with files on disk

using namespace std;

int main () {

	char inputFileName[20] ;   // max length of filename is 19
        char outputFileName[20] ;
	int number , sum , count ;
        ifstream inn ;     //  Declare "inn" as an input file stream variable
			   //  "inn" is an object
        ofstream out;      //  "inn" and "out" are arbitrarily chosen names
			   //  only subject to the usual name conventions and
			   //  not conflicting with anything else named the same

	cout << "Give name file containing data : " ;
	cin  >> inputFileName ; 

	// inputFileName[0]  1. character of name of input file
	// inputFileName[1]  2. character of name of input file
	// inputFileName[2]  3. character of name of input file
	// etc.

	inn.open ( inputFileName ) ;  
	// inn.open ( inputFileName , ios::in ) ;  

	if ( inn.fail() ) {
	   cout << "Could not open input file " << endl ;
	   cout << "Creation of object inn failed." << endl ;
	   exit(1) ;
	}

	/****************************************
	*
	*  Reading through file , one number at a time 
	*  until EOF is encountered
	*  Also : evaluating the sum of all numbers and 
	*         counting how many numbers
	*
	*****************************************/
	count  = 0 ;
	sum    = 0 ;
	number = 0 ;
	do {   
          count++ ;
	  sum = sum + number ;    // alternately :  sum += number;
	  inn >> number ;         // Reading a single number from file
	} while ( ! inn.eof() ) ; // inn.eof = true if eof is encountered for

	inn.close() ;   // Closing connection to filestream inn

  	if ( count == 1 ) {
	   // This occurs when the first read encounters the EOF marker.
	   cout << "Input file empty. Nothing written to output file\n" ;
	   exit(3);
	}


	// Writing result to a file
	cout << "Give name file to write data to : " ;
	cin  >> outputFileName ; 

	out.open ( outputFileName ) ;

        // out.open ( outputFileName , ios::app ) ;  // If you wish to append

        if ( ! out.is_open() ) {
           // The file could not be opened
           cout << "Output file could not be opened.!!!\n" ;
           exit(2) ;
        }


	out << sum << endl ;

	out.close() ;

}
/*
Last revised: 11/01/07
*/


Zig Herzog; hgnherzog@yahoo.com