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

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

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

Simple File I/O.

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

What we will learn about this week:

Chapter 12. Streams and File I/O

File I/O CS 16: Solving Problems with Computers I Lecture #9

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

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.

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

Programming in C/C

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-

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

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

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

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

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

Programming in C/C

C++ Input/Output: Streams

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

CMPS 221 Sample Final

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

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

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Engineering Problem Solving with C++, Etter/Ingber

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

Programming in C/C

C++ Programming Lecture 10 File Processing

BITG 1113: Files and Stream LECTURE 10

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

Input and Output File (Files and Stream )

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

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

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

Lab # 02. Basic Elements of C++ _ Part1

Writing a Good Program. 7. Stream I/O

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

Objects and streams and files CS427: Elements of Software Engineering

A SHORT COURSE ON C++

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

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

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

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

Chapter 14 Sequential Access Files

Week 5: Files and Streams

Chapter 2. Outline. Simple C++ Programs

Chapter 3 - Notes Input/Output

C++ Programming: From Problem Analysis to Program Design, Third Edition

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Fig: iostream class hierarchy

Scientific Computing

What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17.

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

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

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

Software Design & Programming I

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

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

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

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Object Oriented Programming In C++

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSCI 1061U Programming Workshop 2. C++ Basics

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

PROGRAMMING EXAMPLE: Checking Account Balance

C++ Input/Output Chapter 4 Topics

Chapter 21 - C++ Stream Input/Output

Introduction to C++ (Extensions to C)

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

EP241 Computing Programming

System Design and Programming II

Ch 6-2. File Input / Output

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Chapter 2: Introduction to C++

This watermark does not appear in the registered version - Slide 1

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

C++ basics Getting started with, and Data Types.

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

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

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

Unit-V File operations

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

Outline of what we will cover

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

CS242 COMPUTER PROGRAMMING

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

Chapte t r r 9

Lecture 5 Files and Streams

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

A stream is infinite. File access methods. File I/O in C++ 4. File input/output David Keil CS II 2/03. The extractor and inserter form expressions

Transcription:

Chapter 6

In this chapter, you will learn about: Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

Streams and Basic File I/O I refers to the program Input O refers to program Output: I/O means program Input/Output Examples of Input Devices Keyboard File Your program reads input from an Input Device via a stream object Examples of Output Devices Monitor File Your program writes to an Output Device via a stream object

Streams and Basic File I/O A stream is a flow of data. Input stream: Data flows into the program From keyboard, if the input stream is logically connected to the keyboard From a file, if the input stream is logically connected to the file Output stream: Data flows out of the program To the monitor screen, if the output stream is logically connected to the screen To a file, if the output stream is logically connected to the file

Streams Keyboard and Screen Pre-defined streams cin Input stream connected to the keyboard cout Output stream connected to the screen cin and cout are defined in the iostream library Use #include <iostream> in your program You can declare your own streams to use with files.

Streams Files User-defined streams You can define streams to: Read from files (for convenience) Get input from a file Write to files (for persistent storage even after program terminates!) Send output to a file

Streams and Basic File I/O Streams A Stream is a Special type of Variable known as an Object Special kind of Variable (Object)? A Stream variable cannot be used in an assignment statement (unlike: int, double, float, char..) An Object is a special variable associated with a one or more special-purpose functions [We will talk about this shortly]

Stream and Basic File I/O Streams A variable of type Stream, must be: declared before it can be used initialized before it contains valid data By connecting the stream variable to a file Using special-purpose functions Conceptually, the initialized value is the file it is connected to So How do you change its initialized value? By disconnecting from one file and connecting to another file Using special-purpose functions

Input File Stream Variable Declaration Input File Stream Type is: ifstream Declaration involves Two main steps: 1. First, specify following directives: #include <fstream> // include the fstream library using namespace std; 2. Now, declare the stream variable as type ifstream: ifstream in_stream; // in_stream is the input stream variable // name of your chosen

Output File Stream Variable Declaration Output File Stream Type is: ofstream Declaration involves Two main steps: First, specify the following directives: #include <fstream> // includes the fstream library using namespace std; Now declare the ofstream variable: ofstream out_stream; // out_stream is a name of the output stream // variable of your choice

Input Streams Connecting to a File Assuming stream variable is declared, you may now connect the stream variable to the file: To connect the input stream (in_stream) to a file, you open the file: in_stream.open("infile.txt"); Quotes Input stream variable name Special-purpose function File name in the C++ program folder Mandatory period

Input Streams Getting Data from a File Once you have declared the input stream variable (in_stream) and connected the stream to a file, your program can use the input stream variable to read data from the file: Example: Read two input numbers from the file infile.dat and store them in the integer variables first_num, second_num ifstream in_stream; in_stream.open( infile.dat"); int first num, second_num; in_stream >> first_num >> second_num;

Output Streams Connecting to a File Assuming the output stream variable is declared, you may now connect the output stream variable to the file: To connect the output stream variable (out_stream) to a file, you open the file: out_stream.open( outfile.dat"); Quotes Output stream variable name Special-purpose function External File name in the C++ program folder Mandatory period

Output Streams Writing Data to a File Once you have declared the output stream variable (out_stream) and connected the stream to a file, your program can use the input stream variable to write data to a file: Example: Write two numbers from integer variables: first_num and second_num to the file outfile.dat ofstream out_stream; out_stream.open("outfile.dat"); out_stream << First Number = " << first_num << Second Number = " << second_num;

Disconnect Streams Closing the File Your Program should close the File after usage Why? To disconnect the stream from the file What happens if you fail to close the file? File may get corrupted if program terminates abnormally The OS will close the file if the program ends normally

Closing File Syntax To close the input file: in_stream.close( ); To Close the Output file: out_stream.close( );

Intro to Classes and Objects Objects Examples of Object Streams: in_stream, out_stream, cin, cout An Object: A variable that has one or more functions as well as data associated with it Can you list some of the functions associated with the stream objects? Let s analyze the open functions associated with types: ifstream and ofstream

Intro to Classes and Objects Member Functions A function associated with an object is a Member Function The open function is a member function of in_stream, which is of type ifstream But the open function is also a member function of out_stream, which is of type ofstream The two member functions are different One opens a file for input The other opens the file for output

Objects Member Function Names Objects of different types have different member functions Some of these member functions might have the same name Different objects of the same type have the same member functions

Classes A type whose variables are objects, is a class ifstream is the type of the in_stream variable (object) Therefore ifstream is a class The class of an object determines its member functions Example: ifstream in_stream1, in_stream2; ofstream out_stream1, out_stream2; in_stream1.open and in_stream2.open are the same function out_stream1.open and out_stream2.open are the same function, but different from the functions in in_stream1.open and in_stream2.open

Class Member Function Member functions of an object are the member Functions of its class The class determines the member functions of the object The class ifstream has an open function Therefore, every object declared of type ifstream has that open function

Calling_Object.Member_Function_Name(Argument_List); Examples: in_stream.open( infile.dat ); out_stream.open( outfile.dat ); Note: You must specify the object containing the member function The calling object must be separated from the member function by the dot operator

Opening a file could result in Failure: If the file does not exists If the name is incorrectly typed Error message may or may not be generated Success: How do you handle Opening File Failures?

Use the member function fail( ) to test the success of a stream operation fail returns true if the stream operation failed false if successful What do you do when the program catches Stream Errors: Good idea to automatically stop (exit) the program execution

To exit a program, use the function call: exit( ) You must precede the function call with: #include <cstdlib> using namespace std;

Use both member function fail and the function call exit( ) immediately after calling the member function open in_stream.open( infile.dat"); if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1) ; } Return to OS: Convention: Use1 for failure 2 for Success

! When you read from a file, you program should NOT: Generate prompts Echo values read Why? Example Program Reads from Keyboard cout << Enter the number: ; cin >> the number; cout << The number you entered is << the_number Example Program Reads from File ifstream infile; infile >> the_number; The input file must contain the expected data item(s)

"# So far.. Our member function open Creates a new file for output if file name does not exists Overwrites the existing file if it exists What if you wish to append the output to an existing file: important.txt? Use the constant ios::app in the member function open ofstream outstream; outstream.open("important.txt", ios::app); You must include the iostream library priori to this call #include <iostream> If the file does not exist, a new file will be created Why?

"# #include <fstream> #include<iostream> int main() { using namespace std; cout << opening data.txt for appending.\n ; ofstream fout; fout.open( data.txt, ios::app); if (fout.fail() ) { cout << Input file opening failed.\n ; exit(1); } fout << 5 6 pick up sticks.\n << 7 8 ain t C++ great!\n ; fout.close(); cout << End of appending to file.\n return 0; } Original data.txt file 1 2 buckle my shoes. 3 4 shut the door. data.txt file (After Program execution) 1 2 buckle my shoes. 3 4 shut the door. 5 6 pick up sticks. 7 8 ain t C++ great!

$ % Sometimes it is convenient to let the user enter the correct I/O filename from the keyboard Your program should be able to read the text string entered from the key board into a string variable: A text string is a simply sequence of characters How do you declare a variable (my_file) to hold a sequence of 15 characters? char myfile[16]; Precede the declaration with the directive: #include<string>

&' ( $ char my_file[16]; cout << "Enter the file_name "; cin >> my_file; ifstream in_stream; in_stream.open(my_file); if (in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1); }

( Use commands to format the output to Files: The number of spaces between items The number of digits after the decimal point The numeric style: scientific notation for fixed point Show digits after a decimal point Show plus signs in front of positive numbers Left or right justify numbers in a given space

( Output to Screen cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Output to File ofstream out_stream; out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2);

& precision is a member function of class ofstream The Output Following out_stream.precision(2); A total of 2 significant digits 23. 2.2e7 2.2 6.9e-1 0.00069 OR 2 digits after the decimal point 23.56 2.26e7 2.21 0.69 0.69e-4 Calls to precision apply only to the stream named in the call: out_stream

&()&(*+ setf is a member function of class ofstream setf is an abbreviation for set flags A flag is an instruction to do one of two options ios::fixed is a flag The Output Following out_stream.setf(ios::fixed); All floating point numbers Will be written in fixed-point notation, the way we normally expect to see numbers Unsets scientific notation (ios::scientific) Calls to setf apply only to the stream named in the call: out_stream

&()&(*+ setf is a member funtion of class ofstream ios::scientific is a flag The Output Following out_stream.setf(ios::scientific); All floating point numbers Will be written in scientific notation Unsets fixed-point notation (ios::fixed) Calls to setf apply only to the stream named in the call: out_stream

&()&,*+ setf is a member function of class ofstream setf is an abbreviation for set flags The Output Following out_stream.setf(ios::showpoint); All floating point numbers Will show the decimal point even if the trailing digits are zero Calls to setf apply only to the stream named in the call: out_stream

Use the member function width of class ofstream: Example Print number 8 in four spaces ofstream out_stream; out_stream.width(4); cout_stream << 8<< endl; The member function call affects only the trailing output statements

-('.( Left Justified Print number 8 in four spaces and left justified Right Justified Print number 8 in four spaces and right justified ofstream out_stream; out_stream.width(4); cout.setf(ios::left) cout_stream << 8<< endl; ofstream out_stream; out_stream.width(4); cout.setf(ios::right) cout_stream << 8<< endl; Unsets flag ios::right Unsets flag ios::left