Object Oriented Programming: File Handling in C++
Object Oriented Programming: File Handling in C++
8
Declaring File Stream (Step 1)
NOTE:
The variable/ objects inFile and outFile are used as
“handle to refer” files.
Cont…..(Step 2)
• So far we didn’t attach the file with a handle.
– ifstream myFile;
• We must open a file.
• For this we will use a function “Open”.
– myFile.open(Filename);
Note: Absolute / Relative Path for Filename
Cont…..(Step 3)
• Tell the compiler what you want to do with
file i.e read, write or modify .
• Once the file is opened we can read it.
myFile>>c;
myFile>>c1>>c2>>c3;
• It is very important
• ifstream myFile;
myFile.open(“mytext.txt”);
/*If this file does not exists on the disk, the variable
myFile will not be associated with any file. We must
make sure that the file opening process is
successful. */
Cont…
If(!myFile)
{
cout<<“There is some error opening the
file”<<endl;
cout<<“ File cannot be opened”<<endl;
}
else
cout<<“File opened successfully”<<endl;
Example:
#include <fstream.h>
void main()
{ char name[50];
char sal[10];
char dept[30];
ifstream inFile;
inFile.open("myfile.txt");
if(!inFile)
{
cout<<"Can’t open input file"<<endl;
}
while(!inFile.eof())
{
inFile>>name>>sal>>dept;
cout<<name<<"\t“<<sal<<“\t”<<dept<<endl;
}
inFile.close();
} //end of main
Output of the Program
• open(filename,mode)
void main()
{ cout<<"creating a file"<<endl;
ofstream afile("test1.dat");
cout<<"writing to file.."<<endl;
} //end of file
List of File Handling Modes
outFile.close();
}
Try yourself…..
Numbers of
characters to
// char name[100];
int maxChar=100;
int stopchar=‘o’;
inFile.getLine(name,maxChar,stopchar);
Try yourself…..
char next;
do{
cin.get(next);
if(isspace(next))
cout<<‘_’;
else
cout<<next;
} while (next !=‘.’);
Try it yourself !!!!!!
Write a program that creates the output file
“myoutput.txt” that is identical to the file
“myoriginal.txt” except that all the
occurrences of ‘C’ are replace by “C++”.
Random Access Files
• Discuss how to access the files randomly,
forward and backward.
• Current position inside the file.
• Concept of file position ( Pointer into the file)
• tellg( ) and tellp( )----functions for
determining the file pointer position.
Position in a File
• Assume that a file stream myfile is opened for
reading .
• Myfile.tellg( ) gives us the current get position of the
file pointer.
• It returns a whole number of type long, which is the
position of the next character to be read from that
file.
• tellp() function is used to determine the next
position to write a character while writing into a file.
It also returns a long number.
Setting the Position
• How to move forward and backward within the
file????
• seekg( ) and seekp( ) functions
• seekg( )--- takes us to certain position to start
reading.
• seekp( )---> leads the position to write into.
• Both functions require an argument of type long to
let them know the number of bytes to move forward
or backward. (positive and negative number)
Setting the Position
Number of characters
Starting point
to move to
Area in memory
Number of bytes to
be written
main()
{
long pos;
ofstream outfile;
outfile.open(“test.txt”);
outfile.write(“this is an apple”,16);
//write the string in the file
pos=outfile.tellp();
//get the file pointer position
outfile.seekp(pos-7);
// move 7 positions backward
outfile.close();
}
Try it !!!!!!!!
• Write a program that read the contents from
“myfile1.txt” and copies the contents in
reverse order in “outputfile.txt”……..
CPS235: FilesAndStreams 53
reinterpret_cast
• A reinterpret_cast is performed at compile time and does not
change the value of the object to which its operand points
– Instead, it requests that the compiler reinterpret
the operand as the target type (specified in the
angle brackets following the keyword
reinterpret_cast).
• Here we are using a reinterpret case to convert an int* (the
type of the expression &num) to a const char*
• The same conversion would have to be done in case of the
read() function of the istream class
CPS235: FilesAndStreams 54
Writing Bytes with ostream Member
Function write()
• To write an int variable num to the file, use:
outFile.write( reinterpret_cast< const char *
>(&num ), sizeof( num) );
OR
• outFile.write((char *)&num , sizeof( num) );
• This writes the binary version of the number’s 4 bytes
• Function write treats its first argument as a group of bytes by
viewing the object in memory as a const char*, which is a pointer
to a byte (remember that a char is one byte)
• Starting from that location, function write outputs the number of
bytes specified by its second argument, an integer of type size_t
CPS235: FilesAndStreams 55
int main() {
ifstream inCredit( "credit.dat", ios::in );
cout << "Account" << "Last Name“ << "First Name”<< "Balance
<< endl;
56
// read all records from file
while ( ! inCredit.eof() ) {
// display record
if ( client.getAccountNumber() != 0 )
outputLine( client );
return 0;
} // end main
58