IOStream Library

27
IOStream Library IOStream Library Input / Output in C++ Input / Output in C++ Unit - 10 Unit - 10

description

Unit - 10. IOStream Library. Input / Output in C++. Unit Introduction. This unit covers different features in standard IOStream Library. Unit Objectives. After covering this unit you will understand… IOStream library File operations Buffering operations Seeking operations - PowerPoint PPT Presentation

Transcript of IOStream Library

IOStream LibraryIOStream Library

Input / Output in C++Input / Output in C++

Unit - 10Unit - 10

2

Unit IntroductionUnit Introduction

This unit covers different features in This unit covers different features in standard IOStream Librarystandard IOStream Library

3

Unit ObjectivesUnit Objectives

After covering this unit you will After covering this unit you will understand…understand…

IOStream libraryIOStream library File operationsFile operations Buffering operationsBuffering operations Seeking operationsSeeking operations Output stream formattingOutput stream formatting IOStream manipulatorsIOStream manipulators Creating manipulatorsCreating manipulators

4

IOStream IntroductionIOStream Introduction

Input and Output are the basic Input and Output are the basic programming functionsprogramming functions

Without IOStream Library: requires hundreds of lines of code for

usage and manipulation are error prone with dangling pointers,

uninitialized pointers etc

5

IOStream LibraryIOStream Library

IOStream Library helps in:IOStream Library helps in: ease of codingease of coding error handlingerror handling safer and efficient resultssafer and efficient results

Deals with the following I/O functions in a Deals with the following I/O functions in a safe, efficient and easier manner:safe, efficient and easier manner: Standard InputStandard Input Standard OutputStandard Output FilesFiles Memory Blocks

6

IOStreams FeaturesIOStreams Features

Provides an easier interfaceProvides an easier interface Handles Handles menial tasks like closing the file tasks like closing the file

pointer, when the file is not in use etcpointer, when the file is not in use etc Error handling is automatic when I/O Error handling is automatic when I/O

error occurserror occurs Constructor handles all the initialisationConstructor handles all the initialisation Destructor handles all the cleanup tasks Destructor handles all the cleanup tasks

like removing dangling pointers, like removing dangling pointers, memory cleanup etcmemory cleanup etc

7

File IOStreamsFile IOStreams

File IOStreams are simple to use:File IOStreams are simple to use: Declare an Object Declare an Object Use the file I/O functionsUse the file I/O functions Destroy the object (the destructor is Destroy the object (the destructor is

called automatically when the object called automatically when the object goes out of scope)goes out of scope)

8

Example: File IOStreamsExample: File IOStreams#include <fstream.h>#include <fstream.h>

#include <iostream.h>#include <iostream.h>

void main() void main()

{{

const int sz = 100; const int sz = 100; // Buffer size;// Buffer size;

char buf[sz];char buf[sz];

{{

ifstream in(”myfile.cpp"); ifstream in(”myfile.cpp"); // Read// Read

ofstream out(”myfile.out"); ofstream out(”myfile.out"); // Write// Write

int i = 1; int i = 1; // Line counter// Line counter

while(in.get(buf, sz)) while(in.get(buf, sz))

{ { // Line input// Line input

in.get(); in.get(); // get() does not read ‘\n’// get() does not read ‘\n’

cout << buf << endl; cout << buf << endl; // use endl for ‘\n’// use endl for ‘\n’

// File output just like standard I/O:// File output just like standard I/O:

out << i++ << ": " << buf << endl;out << i++ << ": " << buf << endl;

9

Example: File IOStreams Example: File IOStreams (contd.)(contd.)

}}

} } // Destructors close in & out// Destructors close in & out

ifstream in(”myfile.out");ifstream in(”myfile.out");

// More convenient line input:// More convenient line input:

while(in.getline(buf, sz)) while(in.getline(buf, sz))

{ {

char* cp = buf;char* cp = buf;

while(*cp != ':')while(*cp != ':')

{{

cp++;cp++;

} }

cp += 2; cp += 2; // Past ": "// Past ": "

cout << cp << endl; cout << cp << endl;

}}

}}

10

File Open ModesFile Open Modes

You can control the way a file is opened You can control the way a file is opened by changing a default argumentby changing a default argument

These flags can be combined using a These flags can be combined using a bitwise bitwise OROR

The different modes are:The different modes are: ios::inios::in ios::out ios::out ios::app ios::app ios::nocreate ios::nocreate

11

File Open Modes (contd.)File Open Modes (contd.)

ios::noreplace ios::noreplace ios::trunc ios::trunc ios::binaryios::binary

12

Buffering in IOStreamsBuffering in IOStreams

You can buffer all the bytes in a file You can buffer all the bytes in a file using bufferingusing buffering

It provides an easy and efficient It provides an easy and efficient solution to reading files or other I/O solution to reading files or other I/O featuresfeatures

13

Example: Buffering Example: Buffering IOStreamsIOStreams

#include <fstream.h>#include <fstream.h>

#include <iostream.h>#include <iostream.h>

void main() void main()

{{

ifstream in(“myfile.cpp”);ifstream in(“myfile.cpp”);

cout << in.rdbuf(); cout << in.rdbuf(); // outputs entire file// outputs entire file

// another way to output the file// another way to output the file

while (in.get(*cout.rdbuf()))while (in.get(*cout.rdbuf())) // redirects it to cout// redirects it to cout

{{

in.ignore(); in.ignore(); // ignore the terminator ‘\n’// ignore the terminator ‘\n’

}}

}}

14

Seeking in IOStreamSeeking in IOStream

You can move the stream pointer to You can move the stream pointer to different positions and read or write different positions and read or write bytesbytes

There are three seek functions:There are three seek functions: ios::begios::beg From beginning of stream From beginning of stream ios::curios::cur Current position in stream Current position in stream ios::endios::end From end of stream From end of stream

15

Example: Seeking in IOStreamExample: Seeking in IOStream

#include <iostream>#include <iostream>

#include <fstream>#include <fstream>

void main() void main()

{{

ifstream in("Iofile.cpp");ifstream in("Iofile.cpp");

ofstream out("Iofile.out");ofstream out("Iofile.out");

out << in.rdbuf(); out << in.rdbuf(); // Copy file// Copy file

in.close();in.close();

out.close();out.close();

// Open for reading and writing:// Open for reading and writing:

ifstream in2("Iofile.out", ios::in | ios::out);ifstream in2("Iofile.out", ios::in | ios::out);

ostream out2(in2.rdbuf());ostream out2(in2.rdbuf());

cout << in2.rdbuf(); cout << in2.rdbuf(); // Print whole file// Print whole file

out2 << "Where does this end up?";out2 << "Where does this end up?";

out2.seekp(0, ios::beg); out2.seekp(0, ios::beg); // put pointer// put pointer

16

Example: Seeking in IOStream Example: Seeking in IOStream (contd.)(contd.)

out2 << "And what about this?";out2 << "And what about this?";

in2.seekg(0, ios::beg); in2.seekg(0, ios::beg); // get pointer// get pointer

cout << in2.rdbuf();cout << in2.rdbuf();

}}

17

Output Stream Output Stream FormattingFormatting

You can format the output stream in STL, You can format the output stream in STL, just like you can using printf in C++just like you can using printf in C++

The different formatting functions are:The different formatting functions are: Internal formatting dataInternal formatting data

ios::skipws ios::skipws ios::showbase ios::showbase ios::showpoint ios::showpoint ios::uppercase ios::uppercase ios::showpos ios::showpos ios::unitbuf ios::unitbuf

18

Output Stream Formatting Output Stream Formatting (contd.)(contd.)

ios::stdio ios::stdio Format fieldsFormat fields

ios::basefield ios::basefield ios::dec ios::dec ios::hex ios::hex ios::oct ios::oct

ios::floatfield ios::floatfield ios::scientific ios::scientific ios::fixed ios::fixed automaticautomatic

ios::adjustfield ios::adjustfield ios::left ios::left ios::rightios::right

19

Output Stream Formatting Output Stream Formatting (contd.)(contd.)

ios::internalios::internal

Width, fill and precisionWidth, fill and precision int ios::width( ) int ios::width( ) int ios::width(int n) int ios::width(int n) int ios::fill( ) int ios::fill( ) int ios::fill(int n) int ios::fill(int n) int ios::precision( ) int ios::precision( ) int ios::precision(int n)int ios::precision(int n)

20

Iostream ManipulatorsIostream Manipulators

Output stream formatting can be a Output stream formatting can be a tedious tasktedious task

To make things easier to read and write, To make things easier to read and write, a set of manipulators are provideda set of manipulators are provided

The manipulators are:The manipulators are: showbase / noshowbaseshowbase / noshowbase showpos / noshowposshowpos / noshowpos uppercase / nouppercaseuppercase / nouppercase showpoint / noshowpointshowpoint / noshowpoint

21

IOStream Manipulators IOStream Manipulators (contd.)(contd.)

skipws / noskipwsskipws / noskipws left / right / internalleft / right / internal scientific / fixedscientific / fixed

Some manipulators can have arguments, Some manipulators can have arguments, which require <iomanip.h> headerwhich require <iomanip.h> header

The argument supplied manipulators are:The argument supplied manipulators are: setiosflags (fmtflags n)setiosflags (fmtflags n) resetiosflags(fmtflags n) resetiosflags(fmtflags n)

22

IOStream Manipulators IOStream Manipulators (contd.)(contd.)

setbase(base n) setbase(base n) setfill(char n) setfill(char n) setprecision(int n) setprecision(int n) setw(int n)setw(int n)

23

Example: IOExample: IOStream Stream ManipulatorsManipulators

#include <fstream>#include <fstream>

#include <iomanip>#include <iomanip>

void main() void main()

{{

ofstream trc("trace.out");ofstream trc("trace.out");

int i = 47;int i = 47;

float f = 2300114.414159;float f = 2300114.414159;

char* s = "Is there any more?";char* s = "Is there any more?";

trc << setiosflags(ios::unitbuf | ios::showbase | trc << setiosflags(ios::unitbuf | ios::showbase | ios::uppercase | ios::showpos); ios::uppercase | ios::showpos);

trc << i << endl; trc << i << endl; // Default to dec// Default to dec

trc << hex << i << endl;trc << hex << i << endl;

trc << resetiosflags(ios::uppercase) << oct << i;trc << resetiosflags(ios::uppercase) << oct << i;

trc.setf(ios::left, ios::adjustfield);trc.setf(ios::left, ios::adjustfield);

trc << resetiosflags(ios::showbase) << dec trc << resetiosflags(ios::showbase) << dec << setfill('0');<< setfill('0');

trc << "fill char: " << trc.fill() << endl;trc << "fill char: " << trc.fill() << endl;

trc << setw(10) << i << endl;trc << setw(10) << i << endl;

24

Example: IExample: IOStream Manipulators OStream Manipulators (contd.)(contd.)

trc << resetiosflags(ios::showpos) trc << resetiosflags(ios::showpos) << << setiosflags(ios::showpoint) << "prec = " setiosflags(ios::showpoint) << "prec = " << << trc.precision() << endl;trc.precision() << endl;

trc.setf(ios::scientific, ios::floatfield);trc.setf(ios::scientific, ios::floatfield);

trc << f << endl;trc << f << endl;

trc.setf(ios::fixed, ios::floatfield);trc.setf(ios::fixed, ios::floatfield);

trc << f << endl;trc << f << endl;

trc << setprecision(20);trc << setprecision(20);

trc << "prec = " << trc.precision() << endl;trc << "prec = " << trc.precision() << endl;

trc << resetiosflags( ios::showpoint | ios::unitbuf);trc << resetiosflags( ios::showpoint | ios::unitbuf);

}}

25

Creating ManipulatorsCreating Manipulators

You can create your own manipulatorsYou can create your own manipulators The manipulator may or may not have The manipulator may or may not have

argumentsarguments The declaration for The declaration for endl endl isis

ostream& endl(ostream&);ostream& endl(ostream&);

cout << “howdy” << endl;cout << “howdy” << endl;

the the endl endl produces the produces the address address of that of that function function

Applicator calls the function, passing it the Applicator calls the function, passing it the ostream ostream object as an argumentobject as an argument

26

Example: CExample: Creating reating ManipulatorsManipulators

#include <iostream>#include <iostream>

ostream& nl(ostream& os) ostream& nl(ostream& os)

{{

return os << '\n';return os << '\n';

}}

void main() void main()

{{

cout << "newlines" << nl << "between" << nlcout << "newlines" << nl << "between" << nl

<< "each" << nl << "word" << nl;<< "each" << nl << "word" << nl;

}}

/* /*

The expressionThe expression

os << '\n';os << '\n';

calls a function that returns os, which is what is returnedcalls a function that returns os, which is what is returned

from nl from nl

*/*/

27

Unit SummaryUnit Summary

In this unit you have covered …In this unit you have covered … Overview of the IOStream libraryOverview of the IOStream library Different features of IOStreamDifferent features of IOStream IOStream operations & manipulatorsIOStream operations & manipulators Creating custom manipulatorsCreating custom manipulators