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

Similar documents
Writing a Good Program. 7. Stream I/O

Chapter-12 DATA FILE HANDLING

Unit-V File operations

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

Developed By : Ms. K. M. Sanghavi

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

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file

C++ files and streams. Lec 28-31

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

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

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

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

C++ Input/Output Chapter 4 Topics

C++ Programming Lecture 10 File Processing

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

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

IS 0020 Program Design and Software Tools

Object Oriented Programming In C++

Random File Access. 1. Random File Access

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

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

Chapte t r r 9

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

Lecture 9. Introduction

Chapter 6 Topics. While Statement Syntax Count-Controlled Loops Event-Controlled Loops Using the End-of-File Condition to Control Input Data

Chapter 14 Sequential Access Files

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

Streams - Object input and output in C++

Lecture 5 Files and Streams

Study Material for Class XII. Data File Handling

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

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7. Data File Handling

by Pearson Education, Inc. All Rights Reserved. 2

Fall 2017 CISC/CMPE320 9/27/2017

Introduction. Lecture 5 Files and Streams FILE * FILE *

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

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

Chapter 3 - Notes Input/Output

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

Software Design & Programming I

Streams contd. Text: Chapter12, Big C++

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

Module 11 The C++ I/O System

by Pearson Education, Inc. All Rights Reserved. 2

Input and Output File (Files and Stream )

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

Fundamentals of Programming Session 27

Objects and streams and files CS427: Elements of Software Engineering

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

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

System Design and Programming II

CS101 Linux Shell Handout

C++ Input/Output: Streams

File handling Basics. Lecture 7

Advanced I/O Concepts

Chapter 12: Advanced File Operations

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

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

Object Oriented Programming

UNIT V FILE HANDLING

ios ifstream fstream

by Pearson Education, Inc. All Rights Reserved. 2

1. Demonstrates the Conditional Operator

Stream States. Formatted I/O

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

CPE Summer 2015 Exam I (150 pts) June 18, 2015

Page 1

And Even More and More C++ Fundamentals of Computer Science

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

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

COMP322 - Introduction to C++

Chapter 8 File Processing

CS201 Solved MCQs.

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

More File IO. CIS 15 : Spring 2007

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

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

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

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s

BITG 1113: Files and Stream LECTURE 10

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

Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on

Chapter 9 : I/O Streams and Data Files (pp )

Fig: iostream class hierarchy

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

What we will learn about this week:

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

All About: File I/O in C++ By Ilia Yordanov, ; C++ Resources

Chapter 12. Streams and File I/O

THE HONG KONG POLYTECHNIC UNIVERSITY Faculty of Engineering. Computer Programming Closed-book Written Test 3 Date: 28 March 2009 Time: 2:30 3:30 pm

SECTION A (15 MARKS) Answer ALL Questions. Each Question carries ONE Mark. 1 (a) Choose the correct answer: (10 Marks)

Generate error the C++ way

Streams. Rupesh Nasre.

Programming in C/C

CS103L SPRING 2018 UNIT 7: FILE I/O

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

Class 14. Input File Streams. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Lab: Supplying Inputs to Programs

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

Transcription:

Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard C++ library (such as iostream) A library is a collection of object code to be linked to the C++ program to provide additional functionality For different platforms, different libraries (that may use the same name) can be used for I/O functions This allows the C++ program to be less platform dependent It is because I/O is usually quite different from computers to computers. 1 Standard I/O Objects When a C++ program that includes the iostream classes starts, four objects are created and initialized cin - handle input from the standard input, i.e. keyboard cout - handle output to the standard output, i.e. display cerr - handle unbuffered output to the standard error device, i.e. display in a PC clog - handle buffered error messages that are output to the standard error device, i.e. display in a PC. Buffered: Display only when a flush command is received, e.g. endl statement 2

Keyboard and Screen I/O #include <iostream> input data Keyboard executing program output data Screen cin (of type istream) cout (of type ostream) 3 Buffering Output: Buffer to output device Input: Buffer to computer program iostream classes view the flow of data as being a stream of data, one byte following another Buffer is provided in some cases to the stream The stream of data does not send out if the buffer is not full or no flush request is received It is useful in some situations such as written data to disk since the overhead is very large. It is better to do it in single lots rather than byte by byte. Program Data Stream Buffer Hard disk Temporary Memory I/O 4

>> is a binary operator >> is called the input or extraction operator >> is left associative EXPRESSION cin >> age RETURNS VALUE cin STATEMENT cin >> age >> weight ; 5 char xyz[10]; cin >> xyz; Program Keyboard Chan xyz = "Chan" Chan Buffer: Memory in your keyboard 6

NOTE: shows the location of the reading marker STATEMENTS CONTENTS MARKER POSITION int a ; 957 34 1235\n int b ; 128 96\n int c ; a b c cin >> a >> b ; 957 34 957 34 1235\n 128 96\n a b c cin.ignore(100, \n ) ; 957 34 957 34 1235\n 128 96\n a b c cin >> c ; 957 34 128 957 34 1235\n a b c 128 96\n 7 Input using cin cin has been generally used for input data from keyboard int somevariable; cin >> somevariable; It is a global object - doesn t need to define in our own code The operator >> is overloaded such that different kind of data can be read into the buffer of cin and then to somevariable float somevariable1; cin >> somevariable1; double somevariable2; cin >> somevariable2; char somevariable3[100]; cin >> somevariable3; 8

Member functions of cin Input Stream Methods 9 Member functions, e.g. cin.get() As cin is an object, it has its own member functions Helps to obtain the input data in a more flexible way. #include <iostream> cin.get() using namespace std; returns int main() a character from { standard input char ch; while ((ch = cin.get())!= EOF) The loop will stop { if if end-of-file cout << "ch: " << ch << endl; (crtl-z) is is input cout << "\ndone!\n"; EOF: 0xFF return 0; is is a condition 10

Member functions of cin Status methods: 11 This is the "Enter" key (newline character) If we press crtl-z, it becomes End-of-file (EOF) condition. 12

//End of file at keyboard total = 0; Ctrl-D in UNIX cout << Enter blood pressure (Ctrl Z to stop) ; cin >> thisbp; // priming read while (cin) // while last read successful; or while (!cin.eof()) { total = total + thisbp; cout << Enter blood pressure ; cin >> thisbp; // read another cout << total; 13 Member functions, e.g. cin.getline() cin.getline() allows the whole line of data to be input to a string cin.getline(buffer, MAXSIZE); Include NULL, i.e. '\0' at the end The maximum length of data to be read is defined by MAXSIZE Unlike cin, getline() will read in the terminating newline character and throw it away With cin, the terminating newline is not thrown away, but left in the input buffer. cin will neglect,though, any preceding space, tab and newline 14

Why do we use cin.getline()? cin >> abc has been used quite often since the redirection operator >> is overloaded, i.e. such statement can be used no matter abc is a string, an integer or a floating-point number However if abc is a string, cin >> abc allows only string with continuous characters input cin >> abc will stop to read in data if it sees, e.g. a space cin.getline() is different in that getline() can only read in string, but not other data types; however, it will not stop when encountering spaces or tabs. 15 #include <iostream> using namespace std; int main() { char stringone[256]; char stringtwo[256]; char stringthree[256]; cout << "Enter string one: "; cin.getline(stringone,256); cout << "stringone: " << stringone << endl; Notice the space cout << "Enter string two: "; cin >> stringtwo; cout << "stringtwo: " << stringtwo << endl; The >> operator reads until a new-line or a space character is is seen. That s why five six are read to stringthree[] cout << "Enter string three: "; cin.getline(stringthree,256); cout << "stringthree: " << stringthree << endl; return 0; 16

char abc[10], xyz[10]; cin >> abc; cout << "abc: " << abc << endl; cin.getline(xyz,10); cout << "xyz: " << xyz << endl; Keyboard Chan Chan abc = "Chan\0" Buffer : Memory in your keyboard Program xyz ='\0' and then buffer clear The "Enter" code is still in the buffer 17 char abc[10], xyz[10]; cin.getline(abc,10);cout << "abc: " << abc << endl; cin.getline(xyz,10); cout << "xyz: " << xyz << endl; Keyboard Program Chan abc = "Chan\0" Chan Buffer : Memory in your keyboard The "Enter" key has been cleared 18

Output with cout Just as cin, cout is also an object created when the iostream class starts cout represents the standard output, i.e. display The operator << is overloaded such that different kind of data can be sent out Similar to cin, cout also has a number of member functions cout.put(char a) You may write cout.put(a)<<endl; Put the value of character a to output, and return cout cout.write(char *buf, int length) Not including NULL Write length characters in buf to output device, and return cout. 19 #include <iostream> #include <string> using namespace std; int main() { char One[] = "One if by land"; int fulllength = strlen(one); int tooshort = fulllength - 4; int toolong = fulllength + 6; cout.write(one,fulllength) << "\n"; // fulllength=14,return cout after write cout.write(one,tooshort) << "\n"; cout.write(one,toolong) << "\n"; return 0; write() asks the system to write toolong characters. Hence something unexpected is is displayed 20

Other Member Functions cout.width(int a) Set the width of the next output field to a's value cout.fill(char a) Fill the empty field of the output by a's value #include return <iostream> cout. using namespace std; width(6) defines the total int main() width of the field to be 6 { cout << "Start >"; char. cout.width(6); fill('*') fills the empty cout << 123 << "<End\n"; field with * cout << "Start >"; cout.width(6); cout.fill('*'); cout << 123 << "<End\n"; return 0; 21 Formatting numbers for program output ostream Class Methods 22

Exercise 7.1 Write a program that asks the user to 1. Input his/her surname 2. Input his/her first name Input in TWO lines First name can be 1 word or 2 words If the user puts a space between the two words of his first name, add a hyphen to replace the space. Skip all other spaces in front of or after the first name or surname. For example: Chan Tai Ming Chan Tai-Ming Show the whole name after you read the user inputs. Hint: A string is a character array. You can use a loop to check the content of every character of a string one by one, and to display the characters out one by one. 23 File Input and Output C++ provides library functions to help us deal with file accesses File access is usually performed in the following way: Open file Text file To claim from the system the access of a particular file Read data from file Close file Write data to file To perform the read or write instructions To indicate to the system the file access is finished (closed) It is not guaranteed that data can be written to file if not closing. 24

File I/O Using Streams Classes Streams provide a uniform way of dealing with data sending to or reading from files The objects that are used to deal with files are called ofstream and ifstream objects To create an ofstream or ifstream object, we need to include fstream (header file) in our program To open a file for write or read, first create an ofstream or ifstream object with the filename as the input parameter. ofstream fout("myfile.cpp"); ifstream fin("myfile.cpp"); Unlike cin, we can have more than one file being processed in a program. fout and fin are objects but NOT standard objects, unlike cout and cin. Any other names are O.K. 25 Diskette Files for I/O #include <fstream> input data output data disk file C:\myInfile.dat executing program disk file C:\myOut.dat your variable your variable (of type ifstream) (of type ofstream) 26

Statements for using Disk I/O #include <fstream> ifstream myinfile; ofstream myoutfile; myinfile.open( C:\\myIn.dat ); myoutfile.open( C:\\myOut.dat ); // declarations // open files myinfile.close( ); myoutfile.close( ); // close files 27 Opening a file associates the C++ identifier for your file with the physical (disk) name for the file if the input file does not exist on disk, open is not successful if the output file does not exist on disk, a new file with that name is created if the output file already exists, it is erased places a file reading marker at the very beginning of the file, pointing to the first character in it 28

Read or Write Files After opening files, reading or writing files can be done in a similar way as cout or cin After writing/reading, the file should be closed by the member function close() of the ofstream/ifstream objects. #include <iostream> using namespace std; #include <fstream> int main() { ofstream fout("myfile.cpp"); fout << "This line is written to file.\n"; fout.close(); ifstream fin("myfile.cpp"); char ch; while (fin.get(ch)) //NULL if end of file cout << ch; fin.close(); return 0; To see the output, look at the content of the file myfile.cpp Similar to cout and cin.get(ch). If If for any reason myfile.cpp cannot be opened, fout & fin will still be created, but fout.fail() return true. 29 Reading Character-Based Files Use an ifstream object to read data from a text file Syntax: inputfilestream >> variablename The eof() method can be used to test if the end of file has been reached Example: //while not at end of file while(!infile.eof()) 30

Reading 20 Books from file Price of book C:\\book.dat 3.98 P <eoln> 7.41 H <eoln> 8.79 P <eoln>... Hardback or Paperback? WRITE A PROGRAM TO FIND TOTAL VALUE OF ALL BOOKS 31 #include <iostream> // for cout #include <fstream> // for file I/O using namespace std; int main () { float price, total = 0.0 ; // declarations char kind ; int count = 1; ifstream myinfile ( C:\\book.dat ); // myinfile.open( C:\\book.dat ) ; while ( count < 21 ) { myinfile >> price >> kind ; total = total + price ; count ++ ; cout << Total is: << total << endl ; myinfile.close( ) ; return 0 ; 32

Counting Frequency of Alphabetic Characters // Program counts frequency of each alphabetic character in a text file. #include < fstream > #include < iostream > using namespace std; int main ( ) { ifstream datafile ; int freqcount [26]={0 ; // zero out the array char ch, index; datafile.open ( C:\\my.dat ) ; // open and verify success if (! datafile ) { cout << CAN T OPEN INPUT FILE! << endl; return 1; datafile.get ( ch ) ; while ( datafile ) { return 0; // read file one character at a time // while last read was successful if (ch >= A && ch <= Z ) ) ++freqcount [ ch A ]; datafile. get ( ch ) ; // get next character 33 Changing Default Behavior Default behavior of opening a file (by ofstream) is to create it if it doesn t yet exist No effect to input Still truncate for output Overwrite If exists, it deletes all its contents and overwrite on it (truncate) ofstream fout2("myfile.cpp",ios::app); This default behavior can be changed by providing a second parameter to the constructor ios::app File will be opened for appending data to the end of the existing file Open modes of class ios ios::ate Place you at the end of the file (either input or output), but write data at the current position, like trunc ios::trunc Default for ofstream; truncates if it exists ios::in The file (if it exists) will NOT be truncated, the read/write cursor is positioned at the start of the file. ios::ate ios::in is similar to ios::app 34

Writing to Files General form object_name << variable_name; Use ofstream object to write to file like cout was used ofstream outfile( C:\\salary.out, ios::app); outfile << Salary for week was << money; Additional writing appended to file 35 Appending to the End of File #include <fstream> #include <iostream> using namespace std; int main() { ofstream fout("myfile.cpp"); //Default trunc fout << "This line is written to file.\n"; fout.close(); char fname[]="myfile.cpp"; File name can be ofstream fout2(fname,ios::app); supplied by a variable fout2 << "This line is appended to the end of the previous line\n"; fout2.close(); ifstream fin("myfile.cpp"); char ch; while (fin.get(ch)) cout << ch; fin.close(); return 0; The default behavior is is changed To avoid redefining variable, a different name should be provided even for opening the same file 36 36

M //Assume myfile.cpp contains "This line is written to file.\n" ofstream fout2("myfile.cpp", ios::in); fout2 << "Beginning of file"; fout2.close(); Default behavior is is changed to non-truncate. The line will replace the beginning part of the text in in the file; but the rest words, if if any, will be left in in the file. ifstream fin("myfile.cpp"); if (!fin) {cout << "File opening error!\n"; return 0; //The operator! is defined for stream object, if the stream is bad, return false (NULL) char ch; It It is is a good practice to while (fin.get(ch)) check if if anything goes cout << ch; wrong when opening a file fin.close(); return 0; M 37 Editing File seekp has NO effect to ios::app It is often that we need to modify a particular part of a file - editing a file ofstream and ifstream offers 4 member functions that set the current position of an opened file For ofstream seekp(long pos); tellp(); For ifstream seekg(long pos); tellg(); The first position is position 0. seekp sets the current position. pos is is a byte offset from the file beginning tellp tells the current position. Return a byte offset from the file beginning seekg and tellg are similar to seekp and tellp except they are for ifstream 38

#include <fstream> #include <iostream> using namespace std; int main() { ofstream test1file("test1"); cout << "Text written: \n"; cout << "This text is written to file!\n"; //write to screen test1file << "This text is written to file!\n"; test1file.close(); ifstream tin("test1"); tin.seekg(10); Change the current position to to 10 Tell the current position cout << "\ncurrent position: " << tin.tellg() << "\n"; cout << "\ncontent of the file after an offset of 10:\n"; char ch; while (tin.get(ch)) { cout << ch; //display file tin.close(); return 0; 39 Two types of file access: Sequential access: characters are stored and retrieved in a sequential manner Random access: characters can be read or written directly at any position For random access, the ifstream object creates a long integer file position marker representing the offset from the beginning of the file File Position Marker Functions 40

Random File Access seekg()/seekp() functions allow you to move to any position in the file Character position in a data file is zero relative Arguments to seekg()/seekp() functions are the offset into the file and the mode (where the offset is to be calculated from) Mode alternatives: ios::beg: start from beginning of file ios::cur: start from current position ios::end: start from end of file 41 Exercise 7.2 1. Build the program in the last page 2. Run the program in Command Prompt 3. Use the DOS command "dir" to find the file "test1" and display it by using the DOS command "type test1". Can you find the statement as shown in the program? 4. Use seekp such that the word "written" in the file is replaced by "*******". 5. Verify the result by using the DOS commands "dir" and "type test1" again. 42