Streams & Files
Introduction & Basic Idea
A stream is a general name given to a flow of data, it is a series of bytes, i.e. heading from a device to another In case of file streams the two devices connected by the stream: - main memory of computer - secondary memory of computer
Input Stream: source: file on secondary storage destination: main memory
Out Stream: source: main memory destination: file on secondary storage
Advantages of concept of streams
The stream based I/O operations are simple The difference between the working of various devices is abstracted or hidden from the user. So there is simplicity We can overload existing operators on streams, thus making the operations easier
Stream class hierarchy
Root ios ios->>>istream & ostream & fstreambase istream & fstreambase->>> ifstream ostream & fstreambase->>>ofstream istream->>>istream_withassign ostream->>>ostream_withassign iostream->>>iostream_withassign fstreambase & iostream->>>fstream istream & ostream->>>iostream
Points
The extraction operator(>>) is an operator overloading member function of istream class The insertion operator(<<) is an operator overloading member function of ostream class cin is a pre-defined object of istream_withassign class cout is pre-defined object of ostream_withassign class ios is the base class that contains many constants and functions that are common to both input and output operations This class also contains following things: Formatting flags Error status flags File operation modes The ios class contains a pointer to streambuff class, that contains actual memory buffer into which data is read or written
Example
Program that writes character, a number and string in a file #include<iostream.h> #include<fstream.h> int main() { char ch=A; int x=100; char* str=JIET //create an o/p stream, associate it with a file ofstream outfile(outdata.txt); //automatic file open in w mode outfile<<ch<<endl<<x<<endl<<str; cout<<endl<<file written; return 0; // destructor called, file closed automatically }
Error Status Bits( FLAG)
NAME 1 goodbit 2 eofbit 3 failbit PURPOSE Set when there is no error Set when eof reached Set when user operation fails due to premature end of file 4 badbit Set when some invalid operation occur e.g. no buffer is associated with the stream 5 hardfail Unrecoverable error, set bit
Function For Accessing Error Flags
NAME PURPOSE
1 int=eof()
2 int=fail() 3 int=bad() 4 int=good() 5 int=clear() 6 int=clear(bit name)
Returns true if eof file is reached Returns true if fail bit, bad bit or hard flag is set
Returns true if bad bit or hard flag is set Returns true, if everything is ok Clears all the bits to zero Clears specific bit to zero
Error Bits / Error Flags
Error Status Bits(Flags) are defined in ios class. These are simply enumerated data types
Functions for Accessing Error Flags are the member functions of ios class. These can be called by specifying object name and membership operator
Example
Program to copy a source file to a destination file #include<iostream.h> #include<fstream.h> int main() { char ch; //create an input stream object //associate it with the source file ifstream infile("c:/a/source.txt"); //create an output stream object //associate it with destination file ofstream outfile("c:/a/destination.txt"); //repeat loop till eof is reached while(!infile.eof()) { infile.get(ch); outfile<<ch; } cout<<endl<<"copy done"; return 0; }
Open function
We can open a file for various operations with the help of open function Object-name .open (file-name, modes);
Object of fstream class Modes may be more than one mode joined by |(pipeline character)
Open function
File may be closed explicitly, but due to destructor, it is automatically closed Open function is a member function of fstream class
Modes to open a file
Mode in Result
For input operation Default mode for ifstream object Open for output operation Default mode for ofstream object Start writing at eof Truncates the file to zero length, it it exists
out
app trunc
nocreate
noreplace binary
Error when opening, if file does not already exist
Error when opening a file for output , if file already exist open a file in binary mode
Open a file in output mode with a precaution that no existing file is replaced
fstream myfile; myfile.open(outfile.txt,ios::out|ios:noreplace); if(myfile.fail()) { cout<<file is existing; exit(1); }
Note
The ofstream, ifstream and fstream classes have destructors. These destructors contain statements for closing the file. Destructor is called as soon as the scope of the object goes out. So file is closed automatically. Hence there is no need of closing a file explicitly
Binary I/O
using << operator requires more space for a record on disk as compared to the space occupied by the same record in memory This is because normally, each number(int or float) is written as a character string rather than as binary bits of the number
Binary I/O
#include<iostream.h> #include<fstream.h> const int MAX=100; int buff[MAX]; int main() { for(int j=0;j<MAX;j++) buff[j]=j; ofstream os(edata.dat,ios::binary); //create output stream os.write((char*)buff,MAX*sizeof(int)); os.close(); for(j=0;j<MAX;j++) buff[j]=0; ifstream is(edata.dat,ios::binary); is.read((char*)buff,MAX*sizeof(int)); for(j=0;j<MAX;j++) if(buff[j]!=j) { cerr<<Data is incorrect\n; return 1; } cout<<Data is correct\n; return 0; }
Object based I/O
Create a file and write a person type object into it #include<iostream.h> #include<fstream.h> class person { protected: char name[80]; int age; public: void getData() { cout<<Enter name; cin>>name; cout<<Enter age; cin>>age; } };
int main() { person pers; pers.getData(); ofstream outfile(PERSON.DAT,ios::binary); outfile.write((char*)&pers,sizeof(pers)); return 0; }