Fig: iostream class hierarchy

Similar documents
CS2141 Software Development using C/C++ Stream I/O

Module 11 The C++ I/O System

UNIT V FILE HANDLING

UEE1303(1070) S 12 Object-Oriented Programming in C++

Streams - Object input and output in C++

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output

Chapter 12 - C++ Stream Input/Output

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

C++ Programming Lecture 10 File Processing

I/O Streams and Standard I/O Devices (cont d.)

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

C++ Input/Output: Streams

by Pearson Education, Inc. All Rights Reserved. 2

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

CS201 Solved MCQs.

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Objects and streams and files CS427: Elements of Software Engineering

IS 0020 Program Design and Software Tools

File I/O Christian Schumacher, Info1 D-MAVT 2013

Streams in C++ Stream concept. Reference information. Stream type declarations

Object Oriented Programming In C++

We will exclusively use streams for input and output of data. Intro Programming in C++

Introduction to Standard C++ Console I/O. C++ Object Oriented Programming Pei-yih Ting NTOU CS

UNIT V FILE HANDLING

Chapter 3 - Notes Input/Output

Chapter 12. Streams and File I/O

Unit-V File operations

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Streams. Rupesh Nasre.

Object Oriented Programming Using C++ UNIT-3 I/O Streams

Chapter 14 Sequential Access Files

Standard I/O in C and C++

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Engineering Problem Solving with C++, Etter/Ingber

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Chapte t r r 9

Introduction to C++ (Extensions to C)

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Developed By : Ms. K. M. Sanghavi

IBM. C/C++ Legacy Class Libraries Reference SC

Fall 2017 CISC/CMPE320 9/27/2017

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Module C++ I/O System Basics

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Consider the following example where a base class has been derived by other two classes:

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Java IO and C++ Streams

Lecture 5 Files and Streams

10/23/02 21:20:33 IO_Examples

Writing a Good Program. 7. Stream I/O

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Chapter 8 File Processing

COMP322 - Introduction to C++

C++ does not, as a part of the language, define how data are sent out and read into the program

Advanced I/O Concepts

UNIT-5. When a C++ program begins execution, four built-in streams are automatically opened. They are: Stream Meaning Default Device

C++ files and streams. Lec 28-31

Introduction. Lecture 5 Files and Streams FILE * FILE *

What we will learn about this week:

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

EP241 Computing Programming

More File Operations. Lecture 17 COP 3014 Spring april 18, 2018

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Lecture 9. Introduction

Developed By : Ms. K. M. Sanghavi

COMP322 - Introduction to C++

Input/Output Streams: Customizing

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

Setting Justification

Chapter-12 DATA FILE HANDLING

Week 3: File I/O and Formatting 3.7 Formatting Output

CSE 100: STREAM I/O, BITWISE OPERATIONS, BIT STREAM I/O

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

Chapter 15 - C++ As A "Better C"

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

OBJECT ORIENTED DESIGN WITH C++ AN INTRODUCTION

Fundamentals of Programming Session 27

The C++ Input/Output Class Hierarchy

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Input and Output File (Files and Stream )

Streams contd. Text: Chapter12, Big C++

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2

Random File Access. 1. Random File Access

by Pearson Education, Inc. All Rights Reserved. 2

Generate error the C++ way

Basic function of I/O system basics & File Processing

Chapter 3 : Assignment and Interactive Input (pp )

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Getting started with C++ (Part 2)

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

Transcription:

Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams behave in the same way even though the actual physical devices they are connected to may differ substantially. Θ Because all streams behave the same, the same I/O functions can operate on virtually any type of physical device. Fig: iostream class hierarchy Stream Meaning Default Device cin Standard input Keyboard cout Standard output Screen cerr Standard error Screen output clog Buffered Screen version of cerr Θ Streams cin, cout, and cerr correspond to C's stdin, stdout, and stderr. Formatted I/O =========== Θ C++ I/O system allows you to format I/O operations. Θ For example, you can set a field width, specify a number base, or determine how many digits after the decimal point will be displayed. Θ two related but conceptually different ways that you can format data. 1. Directly access members of the ios class. It means, you can set various format status flags defined inside the ios class or call various ios member functions. 2. you can use special functions called manipulators that can be included as part of an I/O expression. 1. Formatting Using the ios Members

Θ ios class declares a bitmask enumeration called fmtflags in which the following values are defined. Θ hex flag causes output to be displayed in hexadecimal. Θ left flag is set, output is left justified. Θ right is set, output is right justified. Θ oct flag causes output to be displayed in octal. Θ dec -To return output to decimal, set the dec flag. Θ showbase - causes the base(decimal,hex,oct) of numeric values to be shown. Θ uppercase If set, these characters are displayed in uppercase. Θ showpos - causes a leading plus sign to be displayed before positive values. Θ showpoint- causes a decimal point and trailing zeros to be displayed for all floating-point output Θ scientific flag- floating-point numeric values are displayed using scientific notation. Θ boolalpha is set, Booleans can be input or output using the keywords true and false. Θ basefield - oct, dec, and hex fields, they can be collectively referred to as basefield. Θ floatfield - scientific and fixed fields can be collectively referenced as floatfield. Setting the Format Flags =================== setf( ) function fmtflags setf(fmtflags flags) Θ This function returns the previous settings of the format flags and turns on those flags specified by flags. E.g: to turn on the showpos flag, you can use this statement: cout.setf(ios::showpos); Θ The following program displays the value 100 with the showpos and showpoint flags turned on. cout.setf(ios::showpoint); cout.setf(ios::showpos); cout << 100.0; // displays +100.000 Θ You can OR together two or more flags,e.g: cout.setf(ios::showpoint ios::showpos); Clearing Format Flags ================= Θ The complement of setf() is unsetf() void unsetf(fmtflags flags);

Θ The flags specified by flags are cleared. Θ E.g Program: cout.setf(ios::uppercase ios::scientific); cout << 100.12; // displays 1.001200E+02 cout.unsetf(ios::uppercase); // clear uppercase cout << "\n" << 100.12; // displays 1.001200e+02 An Overloaded Form of setf( ) ====================== fmtflags setf( fmtflags flags1, fmtflags flags2); Θ only the flags specified by flags2 are affected. Θ They are first cleared and then set according to the flags specified by flags1. Θ previous flags setting is returned. int main( ) cout.setf(ios::showpoint ios::showpos, ios::showpoint); cout << 100.0; // displays 100.000, not +100.000 Θ showpoint is set, but not showpos, since it is not specified in the second parameter. Θ most common use of the two-parameter form of setf( ) is when setting the number base, justification etc. Θ E.g: Θ references to the oct, dec, and hex fields can collectively be referred to as basefield. Θ flags that comprise these groupings are mutually exclusive, means, need to turn off one flag when setting another. Θ output in hexadecimal, some implementations require that the other number base flags be turned off. Θ E.g program

cout.setf(ios::hex, ios::basefield); cout << 100; // this displays 64 Θ basefield flags (i.,e., dec, oct, and hex) are first cleared and then the hex flag is set. Θ only the flags specified in flags2 can be affected by flags specified by flags1. cout.setf(ios::showpos, ios::hex); // error, showpos not set cout << 100 << '\n'; // displays 100, not +100 cout.setf(ios::showpos, ios::showpos); // this is correct cout << 100; // now displays +100 Θ In this program, the first attempt to set the showpos flag fails. Examining the Formatting Flags ========================= Θ To know the current format settings but not alter any. Θ For this, ios includes the member function flags() fmtflags flags(); Θ E.g program: void showflags() ; // show default condition of format flags showflags(); cout.setf(ios::right ios::showpoint ios::fixed); showflags(); // This function displays the status of the format flags. void showflags() long f; long i; f = (long) cout.flags(); // get flag settings

// check each flag for(i=0x4000; i; i = i >> 1) if(i & f) cout << "1 "; else cout << "0 "; cout << " \n"; Setting All Flags ============= fmtflags flags(fmtflags f); Θ allows to set all format flags associated with a stream. Θ the bit pattern found in f is used to set the format flags associated with the stream. void showflags(); // show default condition of format flags showflags(); // showpos, showbase, oct, right are on, others off ios::fmtflags f = ios::showpos ios::showbase ios::oct ios::right; cout.flags(f); // set all flags showflags(); width(), precision(), and fill() ====================== Θ three member functions defined by ios that set the format parameters: i) the field width ii) the precision, and iii) the fill character. Θ when a value is output, it occupies only as much space as the number of characters it takes to display it. However, you can specify a minimum field width by using the width( ) function. streamsize width(streamsize w); Θ w becomes the field width. Θ the previous field width is returned. Θ streamsize type is defined as some form of integer by the compiler. Θ In some implementations, the field width must be set before each output. Θ When outputting floating point values, you can determine the number of digits of precision by using the precision( ) function. streamsize precision( streamsize p);

Θ the precision is set to p, and the old value is returned. Θ when a value uses less than the specified width, the field will be padded with the current fill character(space characer, by default). Θ If the size of the value exceeds the minimum field width, the field will be overrun. Θ when a field needs to be filled, it is filled with spaces. Θ We can specify any other fill character by using the fill( ) function. char fill(char ch); Θ After a call to fill( ), ch becomes the new fill character. Θ old one is returned. E.g program: cout.precision(4) ; cout.width(10); cout << 10.12345 << "\n"; // displays : 10.12 cout.fill('*'); cout.width(10); cout << 10.12345 << "\n"; // displays *****10.12 // field width applies to strings, too cout.width(10); cout << "Hi!" << "\n"; // displays: *******Hi! cout.width(10); cout.setf(ios::left); // left justify cout << 10.12345; // displays: 10.12***** output: 10.12 *****10.12 *******Hi! 10.12***** Θ There are overloaded forms of width( ), precision( ), and fill( ) that obtain but do not change the current setting. char fill( ); streamsize width( ); streamsize precision( );

Using Manipulators to Format I/O ========================== Θ We can alter the format parameters of a stream is through the use of special functions called manipulators that can be included in an I/O expression. E.g: boolalpha Turns on boolapha flag. Input/Output dec Turns on dec flag. Input/Output hex Turns on hex flag. Input/Output endl Output a newline character Output and flush the stream. Θ setiosflags( ) manipulator to directly set the various format flags related to a stream. Θ setfill(int ch) Set the fill character to ch. #include <iomanip> cout << hex << 100 << endl; cout << setfill('?') << setw(10) << 2343.0; Output: 64??????2343 Θ main advantage of using manipulators instead of the ios member functions is that they often allow more compact code to be written. Θ Manipulator setiosflags( ) manipulator to directly set the various format flags related to a stream. #include <iomanip> cout << setiosflags(ios::showpos); cout << setiosflags(ios::showbase); cout << 123 << " " << hex << 123; Θ Manipulator boolapha allows true and false values to be input and output using the words "true" and "false" rather than numbers 1 or 0.

bool b; b = true; cout << b << " " << boolalpha << b << endl; cout << "Enter a Boolean value: "; cin >> boolalpha >> b; cout << "Here is what you entered: Output: 1 true Enter a Boolean value: false Here is what you entered: false C++ File I/O ========= Θ perform file I/O, you must include the header <fstream> Θ These classes are derived from istream, ostream, and iostream, Θ Remember, istream, ostream, and iostream are derived from ios, so ifstream, ofstream, and fstream also have access to all operations defined by ios. Fig: iostream class hierarchy Opening and Closing a File ==================== Θ In C++, you open a file by linking it to a stream. Before you can open a file, you must first obtain a stream. Θ There are three types of streams: input, output, and input/output. ifstream in; ofstream out; fstream io; // input // output // input and output void ifstream::open(const char *filename, ios::openmode mode = ios::in); void ofstream::open(const char *filename, ios::openmode mode = ios::out ios::trunc);

void fstream::open(const char *filename, ios::openmode mode = ios::in ios::out); Θ Second parameters is enumeration defined by ios class. Θ ios::app causes all output to that file to be appended to the end. Θ ios::in value specifies that the file is capable of input(read). Θ ios::out value specifies that the file is capable of output(write). Θ ios::trunc value causes the contents of a preexisting file by the same name to be destroyed. ofstream out; out.open("test", ios::out); Θ If open( ) fails, the stream will evaluate to false when used in a Boolean expression. out.open("test", ios::out); if(!out) cout << "Cannot open file.\n"; // handle error Θ Possible to open file by directly giving filename to the stream object when created. ifstream mystream("myfile"); // open file for input Θ check to see if you have successfully opened a file by using the is_open() Prototype: bool is_open( ); if(!out.is_open()) cout << "File is not open.\n"; //... Θ To close a file, use the member function close( ). out.close(); Θ close( ) function takes no parameters and returns no value. Reading and Writing Text Files ======================= Θ To read from or write to a text file, simply use the << and >> operators the same way you do when performing console I/O. // Reading and writing text file ofstream out("invntry"); // output, normal file

if(!out) cout << "Cannot open INVENTORY file.\n"; out << "Radios " << 39.95 << endl; out << "Toasters " << 19.95 << endl; out << "Mixers " << 24.80 << endl; out.close(); Θ Following program reads the inventory file created by the previous program and displays its contents on the screen: ifstream in("invntry"); // input if(!in) cout << "Cannot open INVENTORY file.\n"; char item[20]; float cost; in >> item >> cost; cout << item << " " << cost << "\n"; in >> item >> cost; cout << item << " " << cost << "\n"; in >> item >> cost; cout << item << " " << cost << "\n"; in.close(); Θ Following is another example of disk I/O. This program reads strings entered at the keyboard and writes them to disk. Θ The program stops when the user enters an exclamation point(!). int main(int argc, char *argv[]) if(argc!=2)

cout << "Usage: output <filename>\n"; ofstream out(argv[1]); // output, normal file if(!out) cout << "Cannot open output file.\n"; char str[80]; cout << "Write strings to disk. Enter! to stop.\n"; do cout << ": "; cin >> str; out << str << endl; while (*str!= '!'); out.close(); When reading text files using the >> operator, keep in mind that certain character translations will occur. For example, white- space characters are omitted. Θ If you want to prevent any character translations, you must open a file for binary access and use the functions discussed in the next section. Unformatted and Binary I/O ===================== Θ there will be times when you need to store unformatted (raw) binary data, not text(executable files, audio/video files etc.) Θ There are functions to do this. Θ Though often we think character and byte are equivalent, it need not be always. Θ While byte is always 8 bit, a character need not be 8- bit(e.g wchat_t type in c++) put( ) and get( ) =========== istream &get(char &ch); ostream &put(char ch); Θ Used to read and write unformatted data. Θ these functions read and write bytes of data as characters. Θ get( ) function reads a single character from the invoking stream and puts that value in ch. Θ function put() writes ch to the stream and returns a reference to the stream. Θ The following program displays the contents of any file, whether it contains text or binary data, on the screen.

int main(int argc, char *argv[]) char ch; if(argc!=2) cout << "Usage: PR <filename>\n"; ifstream in(argv[1], ios::in ios::binary); if(!in) cout << "Cannot open file."; while(in) // in will be false when eof is reached in.get(ch); if(in) cout << ch; Θ when the end-of-file is reached, the stream associated with the file becomes false Θ compact way to code the loop that reads and displays a file. while(in.get(ch)) cout << ch; Θ Program writes into a file using put() int i; ofstream out("chars", ios::out ios::binary); if(!out) cout << "Cannot open output file.\n"; // write all characters to disk

for(i=0; i<256; i++) out.put((char) i); out.close(); read( ) and write( ) ============== Θ to read and write blocks of binary data. istream &read ( char *buf, streamsize num); ostream &write ( const char *buf, streamsize num); Θ read( ) function reads num characters from the invoking stream and puts them in the buffer pointed to by buf. Θ write( ) function writes num characters to the invoking stream from the buffer pointed to by buf. Θ program writes a structure to disk and then reads it back in: #include <cstring> struct status char name[80]; double balance; unsigned long account_num; ; struct status acc; strcpy(acc.name, "Ralph Trantor"); acc.balance = 1123.23; acc.account_num = 34235678; // write data ofstream outbal("balance", ios::out ios::binary); if(!outbal) cout << "Cannot open file.\n"; outbal.write((char *) &acc, sizeof(struct status)); outbal.close();

// now, read back; ifstream inbal("balance", ios::in ios::binary); if(!inbal) cout << "Cannot open file.\n"; inbal.read((char *) &acc, sizeof(struct status)); cout << acc.name << endl; cout << "Account # " << acc.account_num; cout.precision(2); cout.setf(ios::fixed); cout << endl << "Balance: $" << acc.balance; inbal.close(); Θ If the end of the file is reached before num characters have been read, then read( ) simply stops, and the buffer contains as many characters as were available. Θ You can find out how many characters have been read by using another member function, called gcount( ), which has this prototype. streamsize gcount(); Θ program shows another example of read( ) and write( ) and illustrates the use of gcount( ): double fnum[4] = 99.75, - 34.4, 1776.0, 200.1; int i; ofstream out("numbers", ios::out ios::binary); if(!out) cout << "Cannot open file."; out.write((char *) &fnum, sizeof fnum); out.close(); for(i=0; i<4; i++) // clear array fnum[i] = 0.0; ifstream in("numbers", ios::in ios::binary); in.read((char *) &fnum, sizeof fnum); // see how many bytes have been read cout << in.gcount() << " bytes read\n"; for(i=0; i<4; i++) // show values read from file cout << fnum[i] << " ";

in.close(); More get( ) Functions ================ Θ More overloads for get function istream &get(char *buf, streamsize num); istream &get(char *buf, streamsize num, char delim); int get( ); Θ first form reads characters into the array pointed to by buf until either num- 1 characters have been read, a newline is found, or the end of the file has been encountered. Θ newline character is encountered in the input stream, it is not extracted. Instead, it remains in the stream until the next input operation. Θ second form reads characters into the array pointed to by buf until either num- 1 characters have been read, the character specified by delim has been found, or the end of the file has been encountered. Θ The array pointed to by buf will be null terminated by get( ). Θ If the delimiter character is encountered in the input stream, it is not extracted. Instead, it remains in the stream until the next input operation. Θ third overloaded form of get( ) returns the next character from the stream. Θ It returns EOF if the end of the file is encountered. Θ This form of get( ) is similar to C's getc( ) function. getline() ====== istream& getline(char *buf, streamsize num); istream& getline(char *buf, streamsize num, char delim); Θ first form reads characters into the array pointed to by buf until either num - 1 characters have been read, a newline character has been found, or the end of the file has been encountered. Θ The array pointed to by buf will be null terminated by getline( ). If the newline character is encountered in the input stream, it is extracted, but is not put into buf. Θ second form reads characters into the array pointed to by buf until either num-1 characters have been read, the character specified by delim has been found, or the end of the file has been encountered. Θ The array pointed to by buf will be null terminated by getline( ). If the delimiter character is encountered in the input stream, it is extracted, but is not put into buf.

Getline example program: // Read and display a text file line by line. int main(int argc, char *argv[]) if(argc!=2) cout << "Usage: Display <filename>\n"; ifstream in(argv[1]); // input if(!in) cout << "Cannot open input file.\n"; char str[255]; while(in) in.getline(str, 255); // delim defaults to '\n' if(in) cout << str << endl; in.close(); Detecting EOF =========== Θ can detect when the end of the file is reached by using the member function eof(). bool eof( ); Θ returns true when the end of the file has been reached; otherwise it returns false. /* Display contents of specified file in both ASCII and in hex. */ #include <cctype> #include <iomanip> int main(int argc, char *argv[]) if(argc!=2) cout << "Usage: Display <filename>\n";

ifstream in(argv[1], ios::in ios::binary); if(!in) cout << "Cannot open input file.\n"; register int i, j; int count = 0; char c[16]; cout.setf(ios::uppercase); while(!in.eof()) for(i=0; i<16 &&!in.eof(); i++) in.get(c[i]); if(i<16) i--; // get rid of eof for(j=0; j<i; j++) cout << setw(3) << hex << (int) c[j]; for(; j<16; j++) cout << " "; cout << "\t"; for(j=0; j<i; j++) if(isprint(c[j])) cout << c[j]; else cout << "."; cout << endl; count++; if(count==16) count = 0; cout << "Press ENTER to continue: "; cin.get(); cout << endl; in.close(); The ignore( ) Function ================= Θ Used to read and discard characters from the input stream.

istream& ignore( streamsize num=1, int_type delim=eof); Θ reads and discards characters until either num characters have been ignored (1 by default) or the character specified by delim is encountered (EOF by default). Θ int_type is defined as some form of integer. Θ program reads a file called TEST. It ignores characters until either a space is encountered or 10 characters have been read. It then displays the rest of the file. ifstream in("test"); if(!in) cout << "Cannot open file.\n"; /* Ignore up to 10 characters or until first space is found. */ in.ignore(10, ' '); char c; while(in) in.get(c); if(in) cout << c; in.close(); peek() and putback() =============== int_type peek( ); Θ obtain the next character in the input stream without removing it from that stream. Θ returns the next character in the stream or EOF if the end of the file is encountered. istream& putback(char c); Θ return the last character read from a stream to that stream. flush() ===== ostream & flush( );

Θ When output is performed, data is not necessarily immediately written to the physical device linked to the stream. Θ Instead, information is stored in an internal buffer until the buffer is full. Θ you can force the information to be physically written to disk before the buffer is full by calling flush( ). Θ Closing a file or terminating a program also flushes all buffers. SLE: Random Access (to file content): Functions: seekg & seekp, examples EOF