Custom Search

Tuesday, November 4, 2008

Reading And Writing External Files Without an Auxiliary Function

#include <fstream>        //inclusion for file i/o

#include <iostream>        //inclusion for cin/cout

#include <cstdlib>        //inclusion for exit()

using namespace std;


 

void print_headings(ofstream &out_obj);


 

int main()

{int num1,num2,sum;

    

ofstream out_file_obj;        //declare the file stream objects

ifstream in_file_obj;        //ifstream is for input file,

                //ofstream is for output file


 

out_file_obj.open("res.txt");     //open the named file

                    //by invoking the 'open()' method

                    //associated with an ofstream

                    //object. If the file does not

                    //exist it is created. If the file

                    //does exist, it is truncated!!!

                    //So watch out!!


 

                    //file name should follow usual

                    //Dos/Windows/unix file naming

                    //conventions regarding

                    //extensions, etc


 

in_file_obj.open("nums.txt");         //open the named file

                    //by invoking the 'open()' method

                    //associated with an ifstream

                    //object. If the named file

                    //does not exist, the method

                    //fails.


 

if(in_file_obj.fail())        //so, find out if the open failed by

{ cout<<"nums.txt"        //calling the objects 'fail()' method.

<<" could not be opened"    //fail() returns a non-zero value if the

<<" for input\n";        //open did indeed fail; otherwise, it

                    //returns zero.

exit(1);            //terminate the program, signal an error

}


 

// the fstream objects can now be used instead of cout and cin with file

//stream insertion and extraction operators


 

//fstream objects can be passed by reference to functions


 

print_headings(out_file_obj);


 

in_file_obj >> num1 >> num2;    //priming read

while(!in_file_obj.eof())            

{ sum = num1+num2;        

out_file_obj << num1<<"\t\t" <<num2<<"\t\t" <<sum<<endl;

in_file_obj >> num1 >> num2; //read at the bottom of the loop

}


 


 

in_file_obj.close();        //use the 'close()' method to close a file

                    //when you are through using it

out_file_obj.close();

cout<< "program exiting\n";

return 0;

}


 


 

void print_headings(ofstream &out_obj)

{

out_obj << "first num\tsecond num\tsum\n\n";

}


 


 

[pt@cs aix]$ c++ files2.C

[pt@cs aix]$

[pt@cs aix]$ a.out

program exiting

[pt@cs aix]$

[pt@cs aix]$ cat nums.txt

2 40 15

5 67

57

24 34

[pt@cs aix]$

[pt@cs aix]$ cat res.txt

first num    second num    sum


 

2        40        42

15        5        20

67        57        124

24        34        58


 


 

No comments: