UNIT V Contents Steams and Files Stream classes

  • Slides: 69
Download presentation
UNIT – V

UNIT – V

Contents • Steams and Files • Stream classes • Stream Errors • File I/O

Contents • Steams and Files • Stream classes • Stream Errors • File I/O with Streams • File Pointers • File I/O with Member functions • Overloading of extraction and insertion operators • Memory as stream object • Command line arguments • Early V/S Late Binding – in Unit III

C++ I/O • C++ supports all C set of I/O functions • Two reasons

C++ I/O • C++ supports all C set of I/O functions • Two reasons why we don’t use these functions in C++ • I/O methods of C does not supports OOP • I/O methods of C does not handle user defined data types such as class object • C++ uses concept of stream to implement I/O

Streams in C++ • Stream is sequence of bytes • Interface between I/O and

Streams in C++ • Stream is sequence of bytes • Interface between I/O and Program • Two streams • Input stream • Output stream

Input stream Extraction From input stream Input device Output stream Program insert Into output

Input stream Extraction From input stream Input device Output stream Program insert Into output stream

 • Input stream can come from keyboard or any other storage device. •

• Input stream can come from keyboard or any other storage device. • Output stream can go to screen or any other storage device.

C++ stream classes ios ostream iostream ü ios base class ü ios is declared

C++ stream classes ios ostream iostream ü ios base class ü ios is declared as virtual base class so only one copy of members are inherited by iostream

Stream classes Class name Contents ios (general input/output stream class) Basic facilities that are

Stream classes Class name Contents ios (general input/output stream class) Basic facilities that are used by all other input-ouput classes Istream (input stream) Inherits properties of ios Has functions like get(), getline(), read() Contains operator >> Ostream (output stream) Inherits properties of ios Put(), write() Contains operator << Iostream (input/ output stream) Inherits properties of istream and ostream through multiple inheritance and thus contains all input and output functions

Unformatted I/O operations • Using cin & cout • Using >> & << •

Unformatted I/O operations • Using cin & cout • Using >> & << • void get(char *) istream class • char get() istream class(cin) • Put(ch) ostream class(cout) • Getline(char, size) • Write(ch, size)

example #include <iostream> #include<conio. h> using namespace std; int main() { //cout<<"hello"; char c;

example #include <iostream> #include<conio. h> using namespace std; int main() { //cout<<"hello"; char c; // get a character from cin. get(c); // keyboard while(c!='n'){ cout<<c; // display character cin. get(c); //on screen & get another } getch(); return 0; } int main() { //cout<<"hello"; char c; c=cin. get(); while(c!='n'){ cout<<c; cin. get(c); } getch(); return 0; }

#include <iostream> #include<conio. h> using namespace std; int main() { cout<<"enter line"<<"n"; char c;

#include <iostream> #include<conio. h> using namespace std; int main() { cout<<"enter line"<<"n"; char c; c=cin. get(); while(c!='n'){ cout. put(c); cin. get(c); } getch(); return 0; } int main() { cout<<"enter line"<<"n"; char c; c=cin. get(); while(c!='n'){ cout. put(c); cin. get(c); } cout<<"n"; cout. put(65); getch(); return 0; }

#include <iostream> #include<conio. h> using namespace std; int main(){ int size = 20; char

#include <iostream> #include<conio. h> using namespace std; int main(){ int size = 20; char name[20]; cout<<"enetr your full name"<<"n"; cin. getline(name, 20); cout<<"your full name is"<<"n"<<name<<"n"; getch(); return 0; }

#include <iostream> #include<conio. h> #include<string. h> using namespace std; int main(){ char * string

#include <iostream> #include<conio. h> #include<string. h> using namespace std; int main(){ char * string 1 = "object"; cout. write(string 1, 10); getch(); return 0; }

Formatted I/O operations • Formatting output • It includes : ios class functions, flags,

Formatted I/O operations • Formatting output • It includes : ios class functions, flags, manipulators, user- defined output functions • Manipulators in <iomanip. h> ios class format functions manipulators Functions Task Setw() Width() Required field size Setprecision() Precision() Display no. of digits after decimal point Setfill() Fill() Specify a character to be filled in unused portion Setioflags() Setf() Set format flag, e. g left justified or right justified Resetioflags() Unsetf() Clear flag

width cout. width(5); cout<<"123"; cout. width(5); cout<<"45"; // by default right justified

width cout. width(5); cout<<"123"; cout. width(5); cout<<"45"; // by default right justified

precision Ø Output truncated to nearest cent Ø Tailing zeros are truncated Ø Default

precision Ø Output truncated to nearest cent Ø Tailing zeros are truncated Ø Default precision is 6 digits cout. precision(3); cout<<sqrt(2)<<"n"; cout<<3. 14159<<"n"; cout. precision(5); cout<<4. 2992<<"n";

Fill and setf cout. fill('*'); cout. width(10); cout<<"1234"<<"n"; cout. setf(ios: : left, ios: :

Fill and setf cout. fill('*'); cout. width(10); cout<<"1234"<<"n"; cout. setf(ios: : left, ios: : adjustfield); cout. width(15); cout<<"viit"<<"n";

manipulators Cout<<setw(5)<<setprecision(2)<<1. 24567 Cout<<setw(15)<<setioflags(ios: : scientific)<<swrt(3)

manipulators Cout<<setw(5)<<setprecision(2)<<1. 24567 Cout<<setw(15)<<setioflags(ios: : scientific)<<swrt(3)

File • A file is a collection of related data stored in a particular

File • A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of file. • The information / data stored under a specific name on a storage device, is called a file.

ASCII Text files • A text file can be a stream of characters that

ASCII Text files • A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. • It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place.

Binary files • A binary file is no different to a text file. It

Binary files • A binary file is no different to a text file. It is a collection of bytes. In C++ Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences. • No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. • C++ Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer. • It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here.

File Handling in C++ • Why use File Handling • For permanent storage. •

File Handling in C++ • Why use File Handling • For permanent storage. • The transfer of input - data or output - data from one computer to another can be easily done by using files. Data type Description ofstream This is used to create a file and write data on files ifstream This is used to read data from files fstream This is used to both read and write data from/to files

File Stream Classes • Ifstream : - provides input operations. Contains open() with default

File Stream Classes • Ifstream : - provides input operations. Contains open() with default input mode. Inherits the functions get(), getline(), read(), seekg() and tellg() function from istream. Ofstream : - provides output operations. Contains open() with default output mode. Inherits put(), seekp(), teelp() and write() function from ostream. Fstream : - provides support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the function from isteram and ostream classes through iostream

fstream • <fstream> header file. • void open (const char* filename, ios_base: : openmode

fstream • <fstream> header file. • void open (const char* filename, ios_base: : openmode = ios_base: : in | ios_base: : out); • in – file is opened for input. out – file is opened for output. binary – binary file is opened. ate – output position is set to the end of the file when a file is opened. app - all the outputs are appended to the existing contents of the file. trunc – erase data from file. • The default value for fstream mode parameter is in | out. • file is opened for reading and writing when you use fstream class

Functions used in File Handling Function Operation open( ) To create a file close(

Functions used in File Handling Function Operation open( ) To create a file close( ) To close an existing file get( ) Read a single character from a file put( ) write a single character in file. read( ) Read data from file write( ) Write data into file.

Opening a file using open() The function open() can be used to open multiple

Opening a file using open() The function open() can be used to open multiple files that use the same stream object. E. g. file-stream-class stream-object; stream-object. open (“filename”);

OPENING FILE USING open() • Stream-object. open(“filename”, mode) File mode parameter ios: : app

OPENING FILE USING open() • Stream-object. open(“filename”, mode) File mode parameter ios: : app ios: : ate ios: : binary ios: : in ios: : out ios: : nocreate ios: : noreplace ios: : trunc Meaning Append to end of file go to end of file on opening file open in binary mode open file for reading only open file for writing only open fails if the file does not exist open fails if the file already exist delete the contents of the file if it exist

Open and close a file eg: ofstream outfile; // create stream outfile. open (“DATA

Open and close a file eg: ofstream outfile; // create stream outfile. open (“DATA 1”); // connect stream to DATA 1 ……………………………. . outfile. Close(); //disconnect stream from DATA 1 outfile. open(“DATA 2”); //connect stream to DATA 2 ……………………………. . outfile. close(); ………………. .

File Pointer Each file have two associated pointers known as the file pointers. One

File Pointer Each file have two associated pointers known as the file pointers. One of them is called the input pointer (or get pointer) and the other is called the output pointer (or put pointer). The input pointer is used for reading the contents of a given file location and the output pointer is used for writing to a given file location.

Functions for Manipulating File Pointers When we want to move file pointer to desired

Functions for Manipulating File Pointers When we want to move file pointer to desired position then use these function to manage the file pointers. Seekg () = moves get pointer (input) to a specified location Seekp () = moves put pointer (output) to a specified location tellg () = gives the current position of the get pointer tellp () = gives the current position of the put pointer

fout. seekg(0, ios : : beg) -- go to start fout. seekg(0, ios :

fout. seekg(0, ios : : beg) -- go to start fout. seekg(0, ios : : cur) -- stay at current position fout. seekg(0, ios : : end) -- go to the end of file fout. seekg(m, ios : : beg) -- move to m+1 byte in the file fout. seekg(m, ios : : cur) -- go forward by m bytes from the current position fout. seekg(-m, ios : : cur) -- go backward by m bytes from the current position fout. seekg(-m, ios : : end) -- go backward by m bytes from the end

Put( ) and get( ) functions • The function put( ) write a single

Put( ) and get( ) functions • The function put( ) write a single character to the associated stream. Similarly, the function get( ) reads a single character from the associated stream.

read( ) and write( ) functions file. read ((char *)&V , sizeof (V)); file.

read( ) and write( ) functions file. read ((char *)&V , sizeof (V)); file. Write ((char *)&V , sizeof (V)); These function take two arguments. The first is the address of the variable V , and the second is the length of that variable in bytes. The address of variable must be cast to type char * (i. e pointer to character type).

bool is_open( ); • This function returns true if the file is opened and

bool is_open( ); • This function returns true if the file is opened and associated with this stream. Otherwise, it returns false: fstream file; //open file text. txt for input and output file. open("test. txt"); if (!file. is_open()) cout << " Cannot open file!" << endl;

 char get( ) Extracting characters from stream file; //open file text. txt for

char get( ) Extracting characters from stream file; //open file text. txt for input and output file. open("test. txt"); if (!file. is_open()) cout << " Cannot open file!" << endl; //write ten numbers to test. txt for (int i = 0; i != 10; ++i) file << i << endl; //write i with newline character to text. txt file. seekg(ios: : beg); //reset position of the input //read first 5 number from test. txt for (int i = 0; i != 5; ++i) { //show read value on screeen cout << (char)file. get() << endl; }

More functions istream& getline (char* str, streamsize n, char delim = ‘n’); int peek();

More functions istream& getline (char* str, streamsize n, char delim = ‘n’); int peek(); // returns next character seekg (int pos); // set the position of the curser int tellg(); // get the current position of the curser

Steps • File I/O is a five-step process: 1. Include the header file fstream

Steps • File I/O is a five-step process: 1. Include the header file fstream in the program. 2. Declare file stream object. 3. Open the file with the file stream object. 4. Use the file stream object with >>, <<, or other input/output functions. 5. Close the files.

Program to write in a text file #include <fstream> using namespace std; int main(

Program to write in a text file #include <fstream> using namespace std; int main( ) { ofstream fout; fout. open("out. txt"); char str[300] = "Time is a great teacher but unfortunately it kills all its pupils. Berlioz"; //Write string to the file. fout << str; fout. close(); return 0; }

Program to read from text file and display it #include<fstream> #include<iostream> using namespace std;

Program to read from text file and display it #include<fstream> #include<iostream> using namespace std; int main( ) { ifstream fin; fin. open("out. txt"); char ch; while(!fin. eof( )) { fin. get(ch); cout << ch; } fin. close( ); return 0; }

Program to count number of characters #include<fstream> #include<iostream> using namespace std; int main( )

Program to count number of characters #include<fstream> #include<iostream> using namespace std; int main( ) { ifstream fin; fin. open("out. txt"); int count = 0; char ch; while(!fin. eof()) { fin. get(ch); count++; } cout << "Number of characters in file are " << count; fin. close( ); return 0; }

Program to count number of words #include<fstream> #include<iostream> using namespace std; int main( )

Program to count number of words #include<fstream> #include<iostream> using namespace std; int main( ) { ifstream fin; fin. open("out. txt"); int count = 0; char word[30]; while(!fin. eof( )) { fin >> word; count++; } cout << "Number of words in file are " << count; fin. close(); return 0; }

Program to count number of lines #include<fstream> #include<iostream> using namespace std; int main() {

Program to count number of lines #include<fstream> #include<iostream> using namespace std; int main() { ifstream fin; fin. open("out. txt"); int count = 0; char str[80]; while(!fin. eof( )) { fin. getline(str, 80); count++; } cout << "Number of lines in file are " << count; fin. close( ); return 0; }

Program to copy contents of file to another file. #include<fstream> using namespace std; int

Program to copy contents of file to another file. #include<fstream> using namespace std; int main() { ifstream fin; fin. open("out. txt"); ofstream fout; fout. open("sample. txt"); char ch; while(!fin. eof( )) { fin. get(ch); fout << ch; } fin. close( ); fout. close( ); return 0; }

Program to understand all operations #include<iostream> #include<fstream> Class student { Public: Struct stu {

Program to understand all operations #include<iostream> #include<fstream> Class student { Public: Struct stu { char name[20]; int roll; }s; Void put_data(); Void get_data(); };

void student : : put_data() { cout<<"enter name "; cin>>s. name; cout<<"enter roll ";

void student : : put_data() { cout<<"enter name "; cin>>s. name; cout<<"enter roll "; cin>>s. roll; file. Open ("hit. txt“ , ios : : out | ios : : app); file. write ((char *)this, sizeof (student)); file. close(); get_data(); }

void student : : get_data() { int temp; cout<<"enter roll no. "; cin >>temp;

void student : : get_data() { int temp; cout<<"enter roll no. "; cin >>temp; fstream file; file. open ("hit. txt", ios : : in); file. seekg(0, ios: : beg); While (file. read ((char *) this, sizeof (student))) { If (temp==s. roll) { cout<<"student name "<< s. name<<"n"; cout<<"student roll "<< s. roll; } getch (); }

void main() { clrscr(); student st; st. put_data(); }

void main() { clrscr(); student st; st. put_data(); }

One more example fstream file; //open file text. txt for input and output file.

One more example fstream file; //open file text. txt for input and output file. open("test. txt"); //check if file is opened if(!file. is_open()) cout << " Cannot open file!" << endl; / //write a message to file << "This is the first line " << endl << "This is the second line" << endl; file. seekg(ios: : beg); //reset position of the input

//read first 5 number from test. txt for (int i = 0; i !=

//read first 5 number from test. txt for (int i = 0; i != 5; ++i) { //show read value on screeen cout << (char)file. get() << endl; } //get the next character from file char next = file. get(); cout << "The next character is " << (char)next << endl;

//reset position again file. seekg(ios: : beg); char* str = new char[50]; //extract first

//reset position again file. seekg(ios: : beg); char* str = new char[50]; //extract first line into str file. getline(str, 50); //show first line cout << str << endl; //ignore next extracted character file. ignore();

//show the next character without extracting it from file cout << "Peek " <<

//show the next character without extracting it from file cout << "Peek " << (char) file. peek() << endl; //get current position cout << "Current position is " << file. tellg() << endl; //after all work with file is done //close it file. close();

Stream errors • Streams have error state • Flags are set if error occurs

Stream errors • Streams have error state • Flags are set if error occurs

Error Flags Iostate flag Error category ios_base: : goodbit Everything's fine ios_base: : eofbit

Error Flags Iostate flag Error category ios_base: : goodbit Everything's fine ios_base: : eofbit An input operation reached the end of an input sequence ios_base: : failbit An input operation failed to read the expected character, or An output operation failed to generate the desired characters ios_base: : badbit Indicates the loss of integrity of the underlying input or output sequence

 • ios: : goodbit : This state flag indicates that there is no

• ios: : goodbit : This state flag indicates that there is no error with streams. In this case the status variables has value 0. • ios: : eofbit: This state flag indicates that the input operation reached end of input sequence. • ios: : badbit: This state flag indicates that the stream is corrupted and no read/write operation can be performed. • ios: : iostate ios: : rdstate(): This function returns the state of a stream object of type iosteate.

Stream Errors • ios class • bool ios: : good() : This function returns

Stream Errors • ios class • bool ios: : good() : This function returns true when everything is okay, that is , when there is no error conditions. • bool ios: : eof(): This function returns true if the input operation reached end of input sequence. • bool ios: : bad(): This function returns true if the stream is corrupted and no read/write operation can be performed. For example in an irrecoverable read error from a file. • bool ios: : fail(): This functions returns true if the input operation failed to read the expected characters, or that an output operation failed to generate the desired characters. When in fail condition the stream may not be corrupted.

Stream functions to check state ios_base member function Effect bool good() True if no

Stream functions to check state ios_base member function Effect bool good() True if no error flag is set bool eof() True if eofbit is set bool fail() True if failbit or badbit is set bool bad() True if badbit is set bool operator!() As fail() operator void*() Null pointer if fail() and non-null value otherwise iostate rdstate() Value of stream state

Example using std: : ios; using std: : cout; using std: : endl; using

Example using std: : ios; using std: : cout; using std: : endl; using std: : cin; int main() { integer. Value;

cout<<"Before a Bad input operation: " <<"ncin. rdstate(): “<<cin. rdstate() <<"n cin. eof(): "<<cin.

cout<<"Before a Bad input operation: " <<"ncin. rdstate(): “<<cin. rdstate() <<"n cin. eof(): "<<cin. eof() <<"ncin. fail(): “<<cin. fail() <<"ncin. bad(): “<<cin. bad() <<"ncin. good(): "<<cin. good() <<"nn. Expects an integer, but enter a character: "; cin>>integer. Value; cout<<endl;

cout<<"After a bad input operation: " <<"n cin. rdstate(): "<<cin. rdstate() <<"n cin. eof():

cout<<"After a bad input operation: " <<"n cin. rdstate(): "<<cin. rdstate() <<"n cin. eof(): "<<cin. eof() <<"n cin. fail(): "<<cin. fail() <<"n cin. bad(): "<<cin. bad() <<"n cin. good(): "<<cin. good() <<endl;

cin. clear(ios: : goodbit); cout<<"After cin. clear()" <<"ncin. fail(): "<<cin. fail() <<"ncin. good(): "<<cin.

cin. clear(ios: : goodbit); cout<<"After cin. clear()" <<"ncin. fail(): "<<cin. fail() <<"ncin. good(): "<<cin. good() <<endl; return 0; }

Error Handling function in files FUNCTION eof() fail() bad() good() RETURN VALUE AND MEANING

Error Handling function in files FUNCTION eof() fail() bad() good() RETURN VALUE AND MEANING returns true (non zero) if end of file is encountered while reading; otherwise return false(zero) return true when an input or output operation has failed returns true if an invalid operation is attempted or any unrecoverable error has occurred. returns true if no error has occurred.

Command line arguments in C++ • If any input value is passed through command

Command line arguments in C++ • If any input value is passed through command prompt at the time of running of program is known as command line argument. • In Command line arguments application main() function will takes two arguments that is; • argc • argv • argc: argc is an integer type variable and it holds total number of arguments which is passed into main function. It take Number of arguments in the command line including program name. • argv[ ]: argv[] is a char* type variable, which holds actual arguments which is passed to main function.

example #include<iostream> #include<conio> int main(int argc, char* argv[ ]) { int i; cout<<"Total number

example #include<iostream> #include<conio> int main(int argc, char* argv[ ]) { int i; cout<<"Total number of arguments: "<<argc; for(i=0; i< argc; i++) { cout<<endl<< i<<"argument: "<<argv[i]; return 0; } } Run from command prompt with any no. of values passed at run time.

Overloading stream insertion (<<) and extraction (>>) operators • In C++, stream insertion operator

Overloading stream insertion (<<) and extraction (>>) operators • In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input. • We must know following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object istream class 2) These operators must be overloaded as a global function. And if we want to allow them to access private data members of class, we must make them friend.

example #include <iostream> using namespace std; class Complex{ private: int real, imag; public: Complex(int

example #include <iostream> using namespace std; class Complex{ private: int real, imag; public: Complex(int r = 0, int i =0) { real = r; imag = i; } friend ostream & operator << (ostream &out, const Complex &c); friend istream & operator >> (istream &in, Complex &c); };

ostream & operator << (ostream &out, const Complex &c) { out << c. real;

ostream & operator << (ostream &out, const Complex &c) { out << c. real; out << "+i" << c. imag << endl; return out; } istream & operator >> (istream &in, Complex &c) { cout << "Enter Real Part "; in >> c. real; cout << "Enter Imagenory Part "; in >> c. imag; return in; }

int main( ) { Complex c 1; cin >> c 1; cout << "The

int main( ) { Complex c 1; cin >> c 1; cout << "The complex object is "; cout << c 1; return 0; }

 • Output: • Enter Real Part 10 Enter Imaginary Part 20 The complex

• Output: • Enter Real Part 10 Enter Imaginary Part 20 The complex object is 10+i 20

Thank you !!

Thank you !!