Student Book Input / Output in C++

Slides:



Advertisements
Similar presentations
IOStreams CNS 3370 Copyright 2003, Fresh Sources, Inc.
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
I/O Streams as an Introduction to Objects and Classes
File I/O Finished off Colin Cherry standing in for Dr. Lin.
I/O and Program Control Statements Dick Steflik. Overloading C++ provides two types of overloading –function overloading the ability to use the same function.
Programming Stream Manipulators. COMP102 Prog. Fundamentals I: Stream Manipulator Slide 2 Stream Manipulators in iostream.h Library I/O stream manipulators.
CPSC 231 D.H. C++ File Processing 1 Learning Objectives §C++ I/O streams. §Reading and writing sequential files. §Reading and writing random access files.
計算機概論實習 Files and Streams C++ views file as sequence of bytes Ends with end-of-file marker n-1 end-of-file marker 67 This is.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
計算機概論實習 Integral Stream Base expression: dec, oct, hex, setbase, and showbase Use header Integers normally base 10 (decimal) Stream manipulators.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 11 Chapter 21 - C++ Stream Input/Output Outline 21.1Introduction.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Outline 21.1Introduction 21.2Streams Iostream Library Header.
Unformatted and Formatted I/O Operations. 2 Unformatted Input/output is the most basic form of input/output. Unformatted I/O transfers the internal binary.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
C++ Programming Certificate University of Washington Cliff Green
Sayed Ahmed Just E.T.C Technologies Inc. Just E.T.C. Education Inc.
Dale Roberts 1 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Output Formatting. Precision #include... float grade = f; cout.precision(4); cout
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
C++ Streams Lecture-2.
C++ Lecture 8 Monday, 25 August I/O, File, and Preprocessing l An in-depth review of stream input/output l File handling in C++ l C++ preprocessing.
C++ Streams Lecture-2. C++ Streams Stream  A transfer of information in the form of a sequence of bytes I/O Operations:  Input stream: A stream that.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
Fundamental File Processing Operations C++
The C++ Programming Language Streams. Contents u Output Stream u Input Stream u Formatting u Manipulators u Files & Streams.
C++ FILE I/O.
C++ Programming: chapter 6 – iostream 2014, Spring Pusan National University Ki-Joune Li 1.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 11- C++ Stream Input/Output Outline 11.1Introduction 11.2Streams Iostream Library Header.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 31 Thanks for Lecture Slides: C How to Program by Paul Deital &
CS  Inserters and Extractors  Stream State  Files Streams  String Streams  Formatting  Manipulators  Internationalization.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 1 due Friday, 7pm. RAD due next Friday. Presentations week 6. Today: –More details on functions,
#include int main() { char *string1=”C++”; char *string2=”Program”; int m=strlen(string1); int n=strlen(string2); for(int i=1;i
UNIT VI Streams & Files in C++: Stream classes, stream errors, disk file I/O with streams, File pointers, Error handling in file I/O. File I/O with members.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 COMS 261 Computer Science I Title: Functions Date: October 24, 2005 Lecture Number: 22.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
C++ Programming: chapter 6 – iostream 2015, Spring Pusan National University Ki-Joune Li 1.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
Learners Support Publications Working with Files.
CSCI 333 Data Structures I/O with C++ 20 October, 2003.
Lecture 14 Arguments, Classes and Files. Arguments.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Streams & Files in C++:Stream Classes, stream errors, disk file I/O with streams, File Pointers, Error handling in file I/O, File I/O with member functions,
2008YeungNam Univ. SE Lab. 1 C++ views each file as a sequence of bytes terminated by EOF-marker. Header files Files are opened by creating objects of.
CS212: Object Oriented Analysis and Design
Programming with ANSI C ++
Chapter 21 - C++ Stream Input/Output Stream Manipulators
Output Stream Formatting
Chapter 21 - C++ Stream Input/Output
CPSC 231 D.H. C++ File Processing
Standard Input/Output Streams
Standard Input/Output Streams
آشنایی با ساختارها و کار با فایلها
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
files Dr. Bhargavi Goswami Department of Computer Science
Chapter 13: Advanced File and I/O Operations
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Formatting the Output The C++ standard library supplies many manipulators: endl, setw, fixed, showpoint, setprecesion. If we want to use endl, fixed, or.
Programming with ANSI C ++
C++ Stream Input/Output
C++ Programming: chapter 6 – iostream
C++ Programming Lecture 8 File Processing
File I/O in C++ II.
Input/Output Streams, Part 2
Presentation transcript:

Student Book Input / Output in C++ Unit - 10 IOStream Library Input / Output in C++

Student Book Unit Introduction This unit covers different features in standard IOStream Library

Unit Objectives After covering this unit you will understand… Student Book Unit Objectives After covering this unit you will understand… IOStream library File operations Buffering operations Seeking operations Output stream formatting IOStream manipulators Creating manipulators

IOStream Introduction Student Book IOStream Introduction Input and Output are the basic programming functions Without IOStream Library: requires hundreds of lines of code for usage and manipulation are error prone with dangling pointers, uninitialized pointers etc

IOStream Library IOStream Library helps in: Student Book IOStream Library IOStream Library helps in: ease of coding error handling safer and efficient results Deals with the following I/O functions in a safe, efficient and easier manner: Standard Input Standard Output Files Memory Blocks Iostream Library comes with the standard C++ libraries for I/O functions and manipulations

IOStreams Features Provides an easier interface Student Book IOStreams Features Provides an easier interface Handles menial tasks like closing the file pointer, when the file is not in use etc Error handling is automatic when I/O error occurs Constructor handles all the initialisation Destructor handles all the cleanup tasks like removing dangling pointers, memory cleanup etc

File IOStreams File IOStreams are simple to use: Declare an Object Student Book File IOStreams File IOStreams are simple to use: Declare an Object Use the file I/O functions Destroy the object (the destructor is called automatically when the object goes out of scope)

Example: File IOStreams Student Book Example: File IOStreams #include <fstream.h> #include <iostream.h> void main() { const int sz = 100; // Buffer size; char buf[sz]; ifstream in(”myfile.cpp"); // Read ofstream out(”myfile.out"); // Write int i = 1; // Line counter while(in.get(buf, sz)) { // Line input in.get(); // get() does not read ‘\n’ cout << buf << endl; // use endl for ‘\n’ // File output just like standard I/O: out << i++ << ": " << buf << endl; This simple program demonstrates the ease of use in IOstream. This program reads from a file and writes the data to another. The ‘get’ method of IOStream does not read the newline character and therefore it must be thrown away and must have an implicit ‘\n’ after each line read.

Example: File IOStreams (contd.) Student Book Example: File IOStreams (contd.) } } // Destructors close in & out ifstream in(”myfile.out"); // More convenient line input: while(in.getline(buf, sz)) { char* cp = buf; while(*cp != ':') cp++; cp += 2; // Past ": " cout << cp << endl;

Student Book File Open Modes You can control the way a file is opened by changing a default argument These flags can be combined using a bitwise OR The different modes are: ios::in ios::out ios::app ios::nocreate ios::in Opens an input file. Use this as an open mode for an ofstream to prevent truncating an existing file ios::out Opens an output file. When used for an ofstream without ios::app, ios::ate or ios::in, ios::trunc is implied ios::app Opens an output file for appending. ios::ate Opens an existing file (either input or output) and seeks the end. ios::nocreate Opens a file only if it already exists. (Otherwise it fails.) ios::noreplace Opens a file only if it does not exist. (Otherwise it fails.) ios::trunc Opens a file and deletes the old file, if it already exists. ios::binary Opens a file in binary mode. Default is text mode.

File Open Modes (contd.) Student Book File Open Modes (contd.) ios::noreplace ios::trunc ios::binary

Buffering in IOStreams Student Book Buffering in IOStreams You can buffer all the bytes in a file using buffering It provides an easy and efficient solution to reading files or other I/O features Can be useful for manipulating file data. Read the file data, apply manipulation and write back Can also be useful for files that require frequent read/write operations

Example: Buffering IOStreams Student Book Example: Buffering IOStreams #include <fstream.h> #include <iostream.h> void main() { ifstream in(“myfile.cpp”); cout << in.rdbuf(); // outputs entire file // another way to output the file while (in.get(*cout.rdbuf())) // redirects it to cout in.ignore(); // ignore the terminator ‘\n’ } This simple program reads all the data in a buffer and then displays the buffer content.

Student Book Seeking in IOStream You can move the stream pointer to different positions and read or write bytes There are three seek functions: ios::beg From beginning of stream ios::cur Current position in stream ios::end From end of stream

Example: Seeking in IOStream Student Book Example: Seeking in IOStream #include <iostream> #include <fstream> void main() { ifstream in("Iofile.cpp"); ofstream out("Iofile.out"); out << in.rdbuf(); // Copy file in.close(); out.close(); // Open for reading and writing: ifstream in2("Iofile.out", ios::in | ios::out); ostream out2(in2.rdbuf()); cout << in2.rdbuf(); // Print whole file out2 << "Where does this end up?"; out2.seekp(0, ios::beg); // put pointer This example shows the file seek functionality. When the second file is opened in read/write mode, anything put in the file is appended at the end. It then seeks the start of the file and puts the like “and what about this?”

Example: Seeking in IOStream (contd.) Student Book Example: Seeking in IOStream (contd.) out2 << "And what about this?"; in2.seekg(0, ios::beg); // get pointer cout << in2.rdbuf(); }

Output Stream Formatting Student Book Output Stream Formatting You can format the output stream in STL, just like you can using printf in C++ The different formatting functions are: Internal formatting data ios::skipws ios::showbase ios::showpoint ios::uppercase ios::showpos ios::unitbuf Internal formatting data ios::skipws Skip white space. (For input; this is the default.) ios::showbase Indicate the numeric base (dec, oct, or hex) when printing an integral value. The format used can be read by the C++ compiler. ios::showpoint Show decimal point and trailing zeros for floating-point values. ios::uppercase Display uppercase A-F for hexadecimal values and E for scientific values. ios::showpos Show plus sign (+) for positive values. ios::unitbuf “Unit buffering.” The stream is flushed after each insertion. ios::stdio Synchronizes the stream with the C standard I/O system. Format fields ios::basefield ios::dec Format integral values in base 10 (decimal) (default radix).

Output Stream Formatting (contd.) Student Book Output Stream Formatting (contd.) ios::stdio Format fields ios::basefield ios::dec ios::hex ios::oct ios::floatfield ios::scientific ios::fixed automatic ios::adjustfield ios::left ios::right ios::hex Format integral values in base 16 (hexadecimal). ios::oct Format integral values in base 8 (octal). ios::floatfield ios::scientific Display floating-point numbers in scientific format. Precision field indicates number of digits after the decimal point. ios::fixed Display floating-point numbers in fixed format. Precision field indicates number of digits after the decimal point. “automatic” (Neither bit is set.) Precision field indicates the total number of significant digits. ios::adjustfield ios::left Left-align values; pad on the right with the fill character. ios::right Right-align values. Pad on the left with the fill character. This is the default alignment. ios::internal Add fill characters after any leading sign or base indicator, but before the value.

Output Stream Formatting (contd.) Student Book Output Stream Formatting (contd.) ios::internal Width, fill and precision int ios::width( ) int ios::width(int n) int ios::fill( ) int ios::fill(int n) int ios::precision( ) int ios::precision(int n) Width, fill and precision int ios::width( ) Reads the current width. (Default is 0.) Used for both insertion and extraction. int ios::width(int n) Sets the width, returns the previous width. int ios::fill( ) Reads the current fill character. (Default is space.) int ios::fill(int n) Sets the fill character, returns the previous fill character. int ios::precision( ) Reads current floating-point precision. (Default is 6.) int ios::precision(int n) Sets floating-point precision, returns previous precision. See ios::floatfield table for the meaning of “precision.”

Iostream Manipulators Student Book Iostream Manipulators Output stream formatting can be a tedious task To make things easier to read and write, a set of manipulators are provided The manipulators are: showbase / noshowbase showpos / noshowpos uppercase / nouppercase showpoint / noshowpoint showbase / noshowbase: Indicate the numeric base (dec, oct, or hex) when printing an integral value. The format used can be read by the C++ compiler. Showpos / noshowpos: Show plus sign (+) for positive values

IOStream Manipulators (contd.) Student Book IOStream Manipulators (contd.) skipws / noskipws left / right / internal scientific / fixed Some manipulators can have arguments, which require <iomanip.h> header The argument supplied manipulators are: setiosflags (fmtflags n) resetiosflags(fmtflags n) uppercase / nouppercase: Display uppercase A-F for hexadecimal values, and E for scientific values showpoint / noshowpoint: Show decimal point and trailing zeros for floating-point values. skipws / noskipws: Skip white space on input. left / right / internal: Left-align, pad on right. Right-align, pad on left. Fill between leading sign or base indicator and value. scientific / fixed: Use scientific notation setprecision( ) or ios::precision( ) sets number of places after the decimal point. setiosflags (fmtflags n) Sets only the format flags specified by n. Setting remains in effect until the next change, like ios::setf( ). resetiosflags(fmtflags n) Clears only the format flags specified by n. Setting remains in effect until the next change, like ios::unsetf( ).

IOStream Manipulators (contd.) Student Book IOStream Manipulators (contd.) setbase(base n) setfill(char n) setprecision(int n) setw(int n) setbase(base n) Changes base to n, where n is 10, 8, or 16. (Anything else results in 0.) If n is zero, output is base 10, but input uses the C conventions: 10 is 10, 010 is 8, and 0xf is 15. You might as well use dec, oct, and hex for output. setfill(char n) Changes the fill character to n, like ios::fill( ). setprecision(int n) Changes the precision to n, like ios::precision(). setw(int n) Changes the field width to n, like ios::width( ).

Example: IOStream Manipulators Student Book Example: IOStream Manipulators #include <fstream> #include <iomanip> void main() { ofstream trc("trace.out"); int i = 47; float f = 2300114.414159; char* s = "Is there any more?"; trc << setiosflags(ios::unitbuf | ios::showbase | ios::uppercase | ios::showpos); trc << i << endl; // Default to dec trc << hex << i << endl; trc << resetiosflags(ios::uppercase) << oct << i; trc.setf(ios::left, ios::adjustfield); trc << resetiosflags(ios::showbase) << dec << setfill('0'); trc << "fill char: " << trc.fill() << endl; trc << setw(10) << i << endl; Program Output: +47 0X2F 057fill char: +48 +470000000 prec = 6 2.300114e+06 2300114.500000 prec = 20

Example: IOStream Manipulators (contd.) Student Book Example: IOStream Manipulators (contd.) trc << resetiosflags(ios::showpos) << setiosflags(ios::showpoint) << "prec = " << trc.precision() << endl; trc.setf(ios::scientific, ios::floatfield); trc << f << endl; trc.setf(ios::fixed, ios::floatfield); trc << setprecision(20); trc << "prec = " << trc.precision() << endl; trc << resetiosflags( ios::showpoint | ios::unitbuf); }

Creating Manipulators Student Book Creating Manipulators You can create your own manipulators The manipulator may or may not have arguments The declaration for endl is ostream& endl(ostream&); cout << “howdy” << endl; the endl produces the address of that function Applicator calls the function, passing it the ostream object as an argument the endl produces the address of that function. So the compiler says “is there a function I can call that takes the address of a function as its argument?” There is a pre-defined function in Iostream.h to do this; it’s called an applicator. The applicator calls the function, passing it the ostream object as an argument. You don’t need to know how the applicator works to create your own manipulator; you only need to know the applicator exists.

Example: Creating Manipulators Student Book Example: Creating Manipulators #include <iostream> ostream& nl(ostream& os) { return os << '\n'; } void main() cout << "newlines" << nl << "between" << nl << "each" << nl << "word" << nl; /* The expression os << '\n'; calls a function that returns os, which is what is returned from nl */

Unit Summary In this unit you have covered … Student Book Unit Summary In this unit you have covered … Overview of the IOStream library Different features of IOStream IOStream operations & manipulators Creating custom manipulators