SlideShare a Scribd company logo
1 of 30
Chapter: 12


   Stream and Files
              Lecture: 47 and 48
               Date: 12.11.2012
Objectives
   Overview of stream classes

   Showing how to perform file-related activities using streams:
       How to read and write data to files in a variety of ways
       How to handle files or I/O errors
       How files and OOP are related
Streams
   Stream (flow of data)
       A transfer of information in the form of a sequence of bytes

    In C++, a stream is represented by an object of a
    particular class; e.g., cin and cout are objects of
    iostream class.

   I/O Operations:
       Input: A stream that flows from an input device ( i.e.: keyboard,
        disk drive, network connection) to main memory
       Output: A stream that flows from main memory to an output
        device ( i.e.: screen, printer, disk drive, network connection)
keyboard
                  standard
                input stream
                                CPU
                     standard
                      output    MEM
monitor               stream
terminal
console

                                HDD
 What does information
    travel across?
           Streams
keyboard
                  standard
                input stream
                                CPU

                     standard
                      output    MEM
 monitor              stream
 terminal               file
 console               input
                      stream
                      LOAD      HDD
What does information READ
    travel across?                        file
                                files   output
      Streams                           stream
                                        SAVE
                                        WRITE
C++ Stream Input/output
   iostream library has hundreds of I/O capabilities
     iostream: basic input and output
     fstream: file processing

   iostream library contains many I/O related classes:
       istream ( the extraction operator >>, and get(), getline(), read() are
        members of this class)
       ostream (the insertion operator <<, put(), write() are members of
        this class)
   istream and ostream are subclasses of ios base class
   cout is a predefined object of            the iostream_withassign
    class, whereas cin is a                   predefined object of
    istream_withassign class
C++ Stream Input/output
   The classes used for input and output to the video
    display and keyboard are declared in the header file
    iostream, e.g., #include <iostream>

   The classes used specifically for disk file I/O are
    declared in the fstream header file,
    e.g., #include <fstream>

   All of them can be found in the include subdirectory
    of the C++ compiler.
Stream Class Hierarchy
ios Class
   The granddaddy of all the stream classes, and
    contains the majority of the features needed to
    operate C++ streams

   Three most important features of ios class are:
    1)   Formatting flags
    2)   Error-status flags
    3)   File operation mode
ios Formatting Flags

   The formatting flags act as on/off switches that
    specify choices for various aspects of input and
    output format and operation.
ios Formatting Flags

   Since they are the members of the ios class, they
    must follow the name ios and the scope resolution
    operator;
    e.g., ios::showpoint
   All the flags must be set using the setf() and usetf()
    ios member functions;
    e.g., cout.setf(ios::showpoint)
          cout.unsetf(ios::showpoint)
#include <iostream>
#include <conio.h>
using namespace std;

int main(void)
{
   float x = 18.0;
   cout<< x << endl;            //displays 18

  cout.setf(ios::showpoint);
  cout<< x << endl;          //displays 18.0000

  cout.setf(ios::scientific);
  cout<< x << endl;             //displays 1.800000e+001

  cout.unsetf(ios::showpoint);
  cout.unsetf(ios::scientific);

   cout<<x<<endl;               //displays 18
getch();
return 0; }
ios Formatting Flags

   Since they are the members of the ios class, they
    must follow the name ios and the scope resolution
    operator;
    e.g., ios::showpoint
   All the flags must be set using the setf() and usetf()
    ios member functions;
    e.g., cout.setf(ios::showpoint)
          cout.unsetf(ios::showpoint)
ios Formatting Flags

   Many formatting flags can be set using manipulators

   Manipulators are formatting instructions inserted
    directly into a stream; e.g., endl, oct, setw() etc.

   Manipulators come in two flavors:
    1)   No-argument ios manipulators
    2)   ios manipulators with arguments
No-argument ios Manipulators
ios Manipulators with Arguments
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int main(void)
{
   int var = 11;

  cout << setw(8) << 22 << "n";
  cout << setw(8) << 4444 << "n";
  cout << setw(8) << 666666 << endl;

  cout<< var <<“in hexadecimal is ” << hex <<var;

   cout<< setpercision(5) <<20.99055;
getch();
return 0; }
istream Class

   The istream class is derived from ios class and
    performs input specific activities.
istream Class

   cin.get(): inputs a character from stream
    (even white spaces) and returns it

   cin.get( c ): inputs a character from stream
    and stores it in c
istream Class
   cin.get(array, size):
       Accepts 3 arguments: array of characters, the size limit, and a delimiter ( default
        of ‘n’).
       Uses the array as a buffer
       When the delimiter is encountered, it remains in the input stream
       Null character is inserted in the array
       Unless delimiter flushed from stream, it will stay there
   cin.getline(array, size)
       Operates like cin.get(buffer, size) but it discards the delimiter from
        the stream and does not store it in array
       Null character inserted into array
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{

const int SIZE = 10;
char buffer[ SIZE ];

cout << "Enter a sentence:n";
cin.getline( buffer, SIZE );

cout << "nThe sentence entered is:n" << buffer << endl;

getch();
return 0; }
ostream Class

   The ostream class is derived from ios class and
    handles output or insertion activities.
ostream Class
Stream Errors
   Following statements are well-known to us:

 cout<<“Good afternoon”
Or
 cin >> var
What if the user enters “five” instead of “5” for
 integer variable “var” ?
Stream Errors
   Following statements are well-known to us:

 cout<<“Good afternoon”
Or
 cin >> var
What if the user enters “five” instead of “5” for
 integer variable “var” ?

    The compiler will through an error message!
Errors-Status Bits
   The stream error status flags report errors that occur
    in an input or output operation.
Errors-Status Bits
int i;

while(true) // cycle until input OK
 {
  cout << "nEnter an integer: ";
  cin >> i;
  if( cin.good() ) // if no errors
    {
     cin.ignore(10, 'n'); // remove newline
     break; // exit loop
    }
  cin.clear(); // clear the error bits
  cout << "Incorrect input";

  cin.ignore(10, 'n'); // remove newline
 }
cout << "integer is " << i; // error-free integer

More Related Content

What's hot

C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environmentsnchnchl
 
Perl one-liners
Perl one-linersPerl one-liners
Perl one-linersdaoswald
 
Php opcodes sep2008
Php opcodes sep2008Php opcodes sep2008
Php opcodes sep2008bengiuliano
 
Runtime Symbol Resolution
Runtime Symbol ResolutionRuntime Symbol Resolution
Runtime Symbol ResolutionKen Kawamoto
 
N_Asm Assembly numbers (sol)
N_Asm Assembly numbers (sol)N_Asm Assembly numbers (sol)
N_Asm Assembly numbers (sol)Selomon birhane
 
Assembly Language Tutorials for Windows - 03 Assembly Language Programming
Assembly Language Tutorials for Windows - 03 Assembly Language ProgrammingAssembly Language Tutorials for Windows - 03 Assembly Language Programming
Assembly Language Tutorials for Windows - 03 Assembly Language ProgrammingSangram Kesari Ray
 
Something About Dynamic Linking
Something About Dynamic LinkingSomething About Dynamic Linking
Something About Dynamic LinkingWang Hsiangkai
 
system management -shell programming by gaurav raikar
system management -shell programming by gaurav raikarsystem management -shell programming by gaurav raikar
system management -shell programming by gaurav raikarGauravRaikar3
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scriptingAkshay Siwal
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 

What's hot (19)

C5 c++ development environment
C5 c++ development environmentC5 c++ development environment
C5 c++ development environment
 
Perl one-liners
Perl one-linersPerl one-liners
Perl one-liners
 
Embedded C - Lecture 4
Embedded C - Lecture 4Embedded C - Lecture 4
Embedded C - Lecture 4
 
Assembler (2)
Assembler (2)Assembler (2)
Assembler (2)
 
Mips1
Mips1Mips1
Mips1
 
Php opcodes sep2008
Php opcodes sep2008Php opcodes sep2008
Php opcodes sep2008
 
Runtime Symbol Resolution
Runtime Symbol ResolutionRuntime Symbol Resolution
Runtime Symbol Resolution
 
N_Asm Assembly numbers (sol)
N_Asm Assembly numbers (sol)N_Asm Assembly numbers (sol)
N_Asm Assembly numbers (sol)
 
Assembly Language Tutorials for Windows - 03 Assembly Language Programming
Assembly Language Tutorials for Windows - 03 Assembly Language ProgrammingAssembly Language Tutorials for Windows - 03 Assembly Language Programming
Assembly Language Tutorials for Windows - 03 Assembly Language Programming
 
Linux
LinuxLinux
Linux
 
Linux
LinuxLinux
Linux
 
Something About Dynamic Linking
Something About Dynamic LinkingSomething About Dynamic Linking
Something About Dynamic Linking
 
Linux com
Linux comLinux com
Linux com
 
system management -shell programming by gaurav raikar
system management -shell programming by gaurav raikarsystem management -shell programming by gaurav raikar
system management -shell programming by gaurav raikar
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
 
Mysql
MysqlMysql
Mysql
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
x86
x86x86
x86
 

Viewers also liked

Viewers also liked (13)

Lec 49 - stream-files
Lec 49 - stream-filesLec 49 - stream-files
Lec 49 - stream-files
 
Lec9 Transistor Bias Circuits
Lec9 Transistor Bias CircuitsLec9 Transistor Bias Circuits
Lec9 Transistor Bias Circuits
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10
 
Lec 30.31 - inheritance
Lec 30.31 -  inheritanceLec 30.31 -  inheritance
Lec 30.31 - inheritance
 
9781285852744 ppt ch11
9781285852744 ppt ch119781285852744 ppt ch11
9781285852744 ppt ch11
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Managing console input and output
Managing console input and outputManaging console input and output
Managing console input and output
 
File handling
File handlingFile handling
File handling
 
JFET
JFETJFET
JFET
 
file handling c++
file handling c++file handling c++
file handling c++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Object-Oriented Design: Multiple inheritance (C++ and C#)
Object-Oriented Design: Multiple inheritance (C++ and C#)Object-Oriented Design: Multiple inheritance (C++ and C#)
Object-Oriented Design: Multiple inheritance (C++ and C#)
 
JFET
JFETJFET
JFET
 

Similar to Lec 47.48 - stream-files

streams and files
 streams and files streams and files
streams and filesMariam Butt
 
programming language in c&c++
programming language in c&c++programming language in c&c++
programming language in c&c++Haripritha
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesssuserf86fba
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with filesramya marichamy
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with fileskirupasuchi1996
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptxDeepasCSE
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdfTigabu Yaya
 
cs262_intro_slides.pptx
cs262_intro_slides.pptxcs262_intro_slides.pptx
cs262_intro_slides.pptxAnaLoreto13
 

Similar to Lec 47.48 - stream-files (20)

streams and files
 streams and files streams and files
streams and files
 
Console i/o for c++
Console i/o for c++Console i/o for c++
Console i/o for c++
 
programming language in c&c++
programming language in c&c++programming language in c&c++
programming language in c&c++
 
Iostream in c++
Iostream in c++Iostream in c++
Iostream in c++
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequences
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
7512635.ppt
7512635.ppt7512635.ppt
7512635.ppt
 
C++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWAREC++ AND CATEGORIES OF SOFTWARE
C++ AND CATEGORIES OF SOFTWARE
 
Managing console
Managing consoleManaging console
Managing console
 
cs262_intro_slides.pptx
cs262_intro_slides.pptxcs262_intro_slides.pptx
cs262_intro_slides.pptx
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
Unit v
Unit vUnit v
Unit v
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 

More from Princess Sam

Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsPrincess Sam
 
Lec 40.41 - pointers
Lec 40.41 -  pointersLec 40.41 -  pointers
Lec 40.41 - pointersPrincess Sam
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointersPrincess Sam
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functionsPrincess Sam
 
Lec 33 - inheritance
Lec 33 -  inheritanceLec 33 -  inheritance
Lec 33 - inheritancePrincess Sam
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 

More from Princess Sam (11)

Lec 50
Lec 50Lec 50
Lec 50
 
Lec 42.43 - virtual.functions
Lec 42.43 - virtual.functionsLec 42.43 - virtual.functions
Lec 42.43 - virtual.functions
 
Lec 40.41 - pointers
Lec 40.41 -  pointersLec 40.41 -  pointers
Lec 40.41 - pointers
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointers
 
Lec 45.46- virtual.functions
Lec 45.46- virtual.functionsLec 45.46- virtual.functions
Lec 45.46- virtual.functions
 
Lec 37 - pointers
Lec 37 -  pointersLec 37 -  pointers
Lec 37 - pointers
 
Lec 33 - inheritance
Lec 33 -  inheritanceLec 33 -  inheritance
Lec 33 - inheritance
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Lec 36 - pointers
Lec 36 -  pointersLec 36 -  pointers
Lec 36 - pointers
 

Lec 47.48 - stream-files

  • 1. Chapter: 12 Stream and Files Lecture: 47 and 48 Date: 12.11.2012
  • 2. Objectives  Overview of stream classes  Showing how to perform file-related activities using streams:  How to read and write data to files in a variety of ways  How to handle files or I/O errors  How files and OOP are related
  • 3. Streams  Stream (flow of data)  A transfer of information in the form of a sequence of bytes  In C++, a stream is represented by an object of a particular class; e.g., cin and cout are objects of iostream class.  I/O Operations:  Input: A stream that flows from an input device ( i.e.: keyboard, disk drive, network connection) to main memory  Output: A stream that flows from main memory to an output device ( i.e.: screen, printer, disk drive, network connection)
  • 4. keyboard standard input stream CPU standard output MEM monitor stream terminal console HDD What does information travel across? Streams
  • 5. keyboard standard input stream CPU standard output MEM monitor stream terminal file console input stream LOAD HDD What does information READ travel across? file files output Streams stream SAVE WRITE
  • 6. C++ Stream Input/output  iostream library has hundreds of I/O capabilities  iostream: basic input and output  fstream: file processing  iostream library contains many I/O related classes:  istream ( the extraction operator >>, and get(), getline(), read() are members of this class)  ostream (the insertion operator <<, put(), write() are members of this class)  istream and ostream are subclasses of ios base class  cout is a predefined object of the iostream_withassign class, whereas cin is a predefined object of istream_withassign class
  • 7. C++ Stream Input/output  The classes used for input and output to the video display and keyboard are declared in the header file iostream, e.g., #include <iostream>  The classes used specifically for disk file I/O are declared in the fstream header file, e.g., #include <fstream>  All of them can be found in the include subdirectory of the C++ compiler.
  • 9. ios Class  The granddaddy of all the stream classes, and contains the majority of the features needed to operate C++ streams  Three most important features of ios class are: 1) Formatting flags 2) Error-status flags 3) File operation mode
  • 10. ios Formatting Flags  The formatting flags act as on/off switches that specify choices for various aspects of input and output format and operation.
  • 11.
  • 12. ios Formatting Flags  Since they are the members of the ios class, they must follow the name ios and the scope resolution operator; e.g., ios::showpoint  All the flags must be set using the setf() and usetf() ios member functions; e.g., cout.setf(ios::showpoint) cout.unsetf(ios::showpoint)
  • 13. #include <iostream> #include <conio.h> using namespace std; int main(void) { float x = 18.0; cout<< x << endl; //displays 18 cout.setf(ios::showpoint); cout<< x << endl; //displays 18.0000 cout.setf(ios::scientific); cout<< x << endl; //displays 1.800000e+001 cout.unsetf(ios::showpoint); cout.unsetf(ios::scientific); cout<<x<<endl; //displays 18 getch(); return 0; }
  • 14. ios Formatting Flags  Since they are the members of the ios class, they must follow the name ios and the scope resolution operator; e.g., ios::showpoint  All the flags must be set using the setf() and usetf() ios member functions; e.g., cout.setf(ios::showpoint) cout.unsetf(ios::showpoint)
  • 15. ios Formatting Flags  Many formatting flags can be set using manipulators  Manipulators are formatting instructions inserted directly into a stream; e.g., endl, oct, setw() etc.  Manipulators come in two flavors: 1) No-argument ios manipulators 2) ios manipulators with arguments
  • 18. #include <iostream> #include <iomanip> #include <conio.h> using namespace std; int main(void) { int var = 11; cout << setw(8) << 22 << "n"; cout << setw(8) << 4444 << "n"; cout << setw(8) << 666666 << endl; cout<< var <<“in hexadecimal is ” << hex <<var; cout<< setpercision(5) <<20.99055; getch(); return 0; }
  • 19. istream Class  The istream class is derived from ios class and performs input specific activities.
  • 20.
  • 21. istream Class  cin.get(): inputs a character from stream (even white spaces) and returns it  cin.get( c ): inputs a character from stream and stores it in c
  • 22. istream Class  cin.get(array, size):  Accepts 3 arguments: array of characters, the size limit, and a delimiter ( default of ‘n’).  Uses the array as a buffer  When the delimiter is encountered, it remains in the input stream  Null character is inserted in the array  Unless delimiter flushed from stream, it will stay there  cin.getline(array, size)  Operates like cin.get(buffer, size) but it discards the delimiter from the stream and does not store it in array  Null character inserted into array
  • 23. #include <iostream> #include <conio.h> using namespace std; int main() { const int SIZE = 10; char buffer[ SIZE ]; cout << "Enter a sentence:n"; cin.getline( buffer, SIZE ); cout << "nThe sentence entered is:n" << buffer << endl; getch(); return 0; }
  • 24. ostream Class  The ostream class is derived from ios class and handles output or insertion activities.
  • 26. Stream Errors  Following statements are well-known to us: cout<<“Good afternoon” Or cin >> var What if the user enters “five” instead of “5” for integer variable “var” ?
  • 27. Stream Errors  Following statements are well-known to us: cout<<“Good afternoon” Or cin >> var What if the user enters “five” instead of “5” for integer variable “var” ? The compiler will through an error message!
  • 28. Errors-Status Bits  The stream error status flags report errors that occur in an input or output operation.
  • 30. int i; while(true) // cycle until input OK { cout << "nEnter an integer: "; cin >> i; if( cin.good() ) // if no errors { cin.ignore(10, 'n'); // remove newline break; // exit loop } cin.clear(); // clear the error bits cout << "Incorrect input"; cin.ignore(10, 'n'); // remove newline } cout << "integer is " << i; // error-free integer

Editor's Notes

  1. Student Book
  2. Used tootsie roll pieces as data bytes and a large tootsie roll as a line of data on a cardboard card and drawing on the chalkboard.
  3. Used tootsie roll pieces as data bytes and a large tootsie roll as a line of data on a cardboard card and drawing on the chalkboard.