1 / 47

UNIT III

Learn about stream classes in C++ and how they can be used for data flow, file handling, and formatting. Also, understand the advantages of using streams and the hierarchy of stream classes.

jwiseman
Télécharger la présentation

UNIT III

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. UNIT III STREAMS AND FILES

  2. Stream Classes • A stream is flow of data. • It is represented by an object of a particular class. • cin and cout are stream objects. • Different streams are used to represent different kinds of data flow. • Example: the ifstream class represents data flow from input disk files.

  3. Advantages of Streams • C – simplicity ( no need to give formatting character like %d,%c etc.) • We can overload existing operators and functions, such as the insertion (<<) and extraction (>>) operators, to work with classes that you create. • work in the same way as the built-in types, which again makes programming easier and more error free • C++ streams are the best way to write data to files, and also to format data in memory for later use in text input/output windows and other GUI elements. The Stream Class Hierarchy • The stream classes are arranged in a rather complex hierarchy. Figure 12.1 shows the arrangement of the most important of these classes.

  4. >> is a member of the istream class << is a member of the ostream class. Both of these classes are derived from the ios class. The cout object, representing the standard output stream, which is usually directed to the video display, is a predefined object of the ostream_withassign class, which is derived from the ostream class. The cin is an object of the istream_withassign class, which is derived from istream class.

  5. The iostream and the _withassign Classes • The iostream class derived from both istream and ostream, acts only as a base class from which other classes, specifically iostream_withassign, can be derived. • It has no functions of its own (except constructors and destructors). • Classes derived from iostream can perform both input and output. • There are three _withassign classes: • istream_withassign, derived from istream • ostream_withassign, derived from ostream • iostream_withassign, derived from iostream • These 3 _withassign classes are same except that they include overloaded assignment operators so their objects can be copied. • Why do we need separate copyable and uncopyable stream classes? • it’s not a good idea to copy stream class objects. • each such object is associated with a particular streambuf object, which includes an area in memory to hold the object’s actual data. • the istream, ostream, and iostream classes are made uncopyable(by making their overloaded copy constructors and assignment operators private), while the _withassign • classes derived from them can be copied.

  6. Predefined Stream Objects • two predefined stream objects that are derived from the _withassign classes: cin and cout. • cin, an object of istream_withassign, normally used for keyboard input • cout, an object of ostream_withassign, normally used for screen display

  7. Stream Errors

  8. Difference between ios functions and manipulators • ios functions returns value while manipulators does not. • we can not create own ios functions while we can create our own manipulators. • ios functions are single and not possible to be combined while manipulators are possible to be applied in chain. • ios function needs <iostream> while manipulators needs <iomanip> • ios functions are member functions while manipulators are non-member functions.

  9. The ios Class • - granddaddy of all the stream classes, and contains the majority of the features to operate C++ streams. • The three most important features are the formatting flags, the error-status flags, and the file operation mode.

  10. The formatting flags are members of the ios class • Example: ios::skipws. • All the flags can be set using the setf() and unsetf() ios member functions. • Example: • cout.setf(ios::left); // left justify output text • cout >> “This text is left-justified”; • cout.unsetf(ios::left); // return to default (right justified) • Manipulators (Many formatting flags can be set using manipulators) • -Manipulators are formatting instructions inserted directly into a stream. • -Example: endl, which sends a newline to the stream and flushes it: • cout << “To each his own.” << endl; • setiosflags() manipulator: • cout << setiosflags(ios::fixed) // use fixed decimal point • << setiosflags(ios::showpoint) // always show decimal point • << var;

  11. Manipulators come in two flavors: those that take an argument and those that don’t. • insert these manipulators directly into the stream. • For example, to output var in hexadecimalformat, you can say • cout << hex << var; • -manipulators affect only the data that follows them in the stream, not the data that precedes them.

  12. Table 12.3 summarizes the important manipulators that take arguments. -need the IOMANIP header file for these functions.

  13. Formatting Nmbers This program prints a floating-point number called fpn in a field 10 characters wide, with two digits to the right of the decimal point: cout << setiosflags(ios::fixed) //fixed (not exponential) << setiosflags(ios::showpoint) //always show decimal point << setprecision(2) //two decimal places << setw(10) //field width 10 << fpn; //finally, the number Functions The ios class contains a number of functions that you can use to set the formatting flags and perform other tasks.

  14. These functions are called for specific stream objects using the normal dot operator. • Examples: • -to set the field width , • cout.width(14); • - to set the fill character to an asterisk, • cout.fill(‘*’); • use several functions to manipulate the ios formatting flags directly. • For example, to set left justification, use • cout.setf(ios::left); • - To restore right justification, use • cout.unsetf(ios::left);

  15. These functions are called for specific stream objects using the normal dot operator. • Examples: • -to set the field width , • cout.width(14); • - to set the fill character to an asterisk, • cout.fill(‘*’); • use several functions to manipulate the ios formatting flags directly. • For example, to set left justification, use • cout.setf(ios::left); • - To restore right justification, use • cout.unsetf(ios::left); • -A two-argument version of setf() uses the second argument to reset all the flags of a particular type or field. Then the flag specified in the first argument is set. (so it is easier to reset the relevant flags before setting a new one.) • Example: cout.setf(ios::left, ios::adjustfield);

  16. The istream Class - derived from ios, performs input-specific activities, or extraction.

  17. -Most of them operate on the cin object, which usually represents the data flow from the keyboard. -The last four deal with disk files.

  18. The ostream class: handles output or insertion activities. -The last four functions in this table deal with disk files.

  19. FILE HANDLING CONCEPTS This requires another standard C++ library called fstream, which defines three new data types: • ofstream This data type represents the output file stream and is used to create files and to write information to files. Inherits put(), seekp(),tellp() and write() functions from ostream. • ifstream This data type represents the input file stream and is used to read information from files. Inherits the functions get(), getline(), read(), seekg() and tellg() functions from istream. • fstream   This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.

  20. Opening and Closing a file Closing a file fout.close(); fin.close(); • Opening File Using Constructor Syntax: Stream object(“filename”); ofstreamfout(“results”); //output only ifstream fin(“data”); //input only • Opening File Using Open()  syntax: Stream object.open(“filename”, mode) ofstreamofile; ofile.open(“data1”); ifstreamifile; ifile.open(“data2”);

  21. File Mode Parameters File mode parameter Meaning ios::app Append to end of file ios::ate go to end of file on opening ios::binary file open in binary mode ios::in open file for reading only ios::out open file for writing only ios::nocreate open fails if the file does not exist ios::noreplace open fails if the file already exist ios::trunc delete the contents of the file if it exist

  22. Input And Output Operation • put() and get() function The function put() writes a single character to the associated stream. Similarly, the function get () reads a single character from the associated stream. example : • file.get(ch); • file.put(ch);

  23. write() and read() function write() and read() functions write and read blocks of binary data. example: file.read((char *)&obj, sizeof(obj)); file.write((char *)&obj, sizeof(obj));

  24. File Pointers And Their Manipulation • ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation. • ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written. • Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream).

  25. 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

  26. The other prototype for these functions is: seekg(offset, refposition ); seekp(offset, refposition ); • The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class. ios::beg start of the file ios::cur current position of the pointer ios::end end of the file example: file.seekg(-10, ios::cur);

  27. Specifying the Position

  28. Specifying the Offset

  29. Error Handling Function function return value and meaning eof() returns true (non zero) if end of file is encountered while reading; otherwise return false(zero) fail() return true when an input or output operation has failed bad() returns true if an invalid operation is attempted or any unrecoverable error has occurred. good() returns true if no error has occurred.

  30. Example • Output: • Enter a string • Programming • Programming #include<iostream.h> #include<fstream.h> #include<string.h> int main() { char string[80]; cout<< “Enter a string \n”; cin >> string; intlen=strlen(string); fstream file; file.open(“TEXT”, ios::in | ios::out); for( inti=0; i<len; i++) file.put(string [i]); file.seekg(0); char ch; while(file) { file.get(ch); cout<<ch; } return 0; }

  31. Basic Operation On Text File In C++ • Program to write in a text file #include<fstream.h> int main() { ofstreamfout; fout.open("out.txt"); char str[300]="Time is a great teacher but unfortunately it kills all its pupils. Berlioz"; fout<<str; fout.close(); return 0; }

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

  33. Program to count number of characters. #include<fstream.h> #include<conio.h> int main() { ifstream fin; fin.open("out.txt"); clrscr(); char ch; int count=0; while(!fin.eof()) { fin.get(ch); count++; } cout<<"Number of characters in file is "<<count; fin.close(); getch(); return 0; }

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

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

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

  37. Read & Write Example: // open a file in read mode. ifstreaminfile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // write the data at the screen. cout << data << endl; // again read the data from the file and display it. infile >> data; cout << data << endl; // close the opened file. infile.close(); return 0; } Output: Writing to the file Enter your name: Zara Enter your age: 9 Reading from the file Zara 9 #include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // open a file in write mode. ofstreamoutfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // write inputted data into the file. outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // again write inputted data into the file. outfile << data << endl; // close the opened file. outfile.close();

  38. Working with multiple files: fin.close(); fin.open(“capital”); //connect “capital” cout << “\n Contents of capital file \n”; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); return 0; } Output: Contents of country file United States of America United Kingdom South Korea Contents of capital file Washington London Seoul #include <iostream.h> #include<fstream.h> int main() { ofstreamfout; fout.open(“country”); fout<< “United States of America \n”; fout<< “United Kingdom \n”; fout<< “South Korea \n”; fout.close(); fout.open(“capital”); fout<<”Washington \n”; fout<<”London \n”; fout<<”Seoul \n”; fout.close(); // Reading the files const int N=80; // size of line char line[N]; ifstream fin; fin.open(“country”); cout<< “contents of country file \n”; while(fin) { fin.getline(line,N); //read a line cout<<line; }

  39. Reading from two files simultaneously fin1.getline(line, SIZE); cout <<”Capital of”<<line; if(fin2.eof() !=0) { Cout<< “Exit from capital \n”; exit(1); } fin2.getline(line,SIZE); cout <<line<<”\n”; } return 0; } Output: Capital of United States of America Washington Capital of United Kingdom London Capital of South Korea Seoul #include <iostream.h> #include <fstream.h> #include <stdlib.h> int main() { const int SIZE=80; char line[SIZE]; ifstream fin1, fin2; //Create two input streams fin1.open(“country”); fin2.open(“capital”); for( inti=1; i<=10; i++) { if (fin1.eof() !=0) { Cout<< “Exit from country \n”; exit(1); }

  40. Error Handling in File I/O -Reacting to errors -Analyzing errors

  41. File I/O with Member Functions Objects That Read and Write Themselves Classes That Read and Write Themselves -Static Functions -Size of Derived Objects

  42. Overloading the Extraction and Insertion Operators • Overloading for cout and cin Here’s an example, ENGLIO, that overloads the insertion and extraction operators for the Distance class so they work with cout and cin. // englio.cpp // overloaded << and >> operators #include <iostream> using namespace std; class Distance //English Distance class { private: int feet; float inches; public:

  43. Distance() : feet(0), inches(0.0) //constructor (no args) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } friend istream& operator >> (istream& s, Distance& d); friend ostream& operator << (ostream& s, Distance& d); }; //-------------------------------------------------------------- istream& operator >> (istream& s, Distance& d) //get Distance { //from user cout << “\nEnter feet: “; s >> d.feet; //using cout << “Enter inches: “; s >> d.inches; //overloaded return s; //>> operator } //-------------------------------------------------------------- ostream& operator << (ostream& s, Distance& d) //display { //Distance s << d.feet << “\’-” << d.inches << ‘\”’; //using return s; //overloaded } //<< operator

  44. int main() { Distance dist1, dist2; //define Distances Distance dist3(11, 6.25); //define, initialize dist3 cout << “\nEnter two Distance values:”; cin >> dist1 >> dist2; //get values from user //display distances cout << “\ndist1 = “ << dist1 << “\ndist2 = “ << dist2; cout << “\ndist3 = “ << dist3 << endl; return 0; } Enter feet: 10 Enter inches: 3.5 Enter feet: 12 Enter inches: 6 dist1 = 10’-3.5” dist2 = 12’-6” dist3 = 11’-6.25”

  45. MultiFile Programs

  46. Creating a Multifile Program • Header Files • Directory • Projects Interfile Communication

More Related