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

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

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

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

Simple 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

Chapter 12. Streams and File I/O

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

What we will learn about this week:

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.

Programming in C/C

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

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

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

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

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

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

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

C++ Input/Output: Streams

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

Objects and streams and files CS427: Elements of Software Engineering

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

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

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Pre- Defined Func-ons in C++ Review for Midterm #1

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

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

Programming in C/C

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

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Getting started with C++ (Part 2)

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

Week 5: Files and Streams

COMP322 - Introduction to C++

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Programming in C/C

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

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

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

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

1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A.

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

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

More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

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

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

C++ Programming Lecture 10 File Processing

CMPS 221 Sample Final

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

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-

Chapter 14 Sequential Access Files

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

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

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

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

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.

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

MIPS Assembly: More about MIPS Instructions Using Functions in MIPS CS 64: Computer Organization and Design Logic Lecture #8

Setting Justification

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

C++ Basics 1 CS 16: Solving Problems with Computers I Lecture #3

WARM UP LESSONS BARE BASICS

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Chapter 3 - Notes Input/Output

Input and Output File (Files and Stream )

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

PIC 10A. Review for Midterm I

PIC 10A. Final Review: Part I

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

BITG 1113: Files and Stream LECTURE 10

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

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

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

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

Lecture 14: more class, C++ streams

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

C++ for Python Programmers

System Design and Programming II

Advanced I/O Concepts

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

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

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:

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

CSCE 206: Structured Programming in C++

CS242 COMPUTER PROGRAMMING

Writing a Good Program. 7. Stream I/O

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

Transcription:

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9 Ziad Matni Dept. of Computer Science, UCSB

Midterm Exam grades out! Announcements If you want to see your exams, visit your lab TA during his/her office hours You will only be able to view exams in their (or my) office You will not be allowed to take the exams out of the office 11/1/2017 Matni, CS16, Fa17 2

I/O Data Streams and File I/O Lecture Outline An introduction to Objects and Member Functions Handling File I/O Errors 11/1/2017 Matni, CS16, Fa17 4

File I/O Read (input) from a file Usually done from beginning to the end of file (not always) No backing up to read something again (but you can start over) Similar to how it s done from the keyboard Write (output) to a file Usually done from beginning to end of file (not always) No backing up to write something again (but you can start over) Similar to how it s done to the screen 11/1/2017 Matni, CS16, Fa17 5

Stream Variables for File I/O You have to use stream variables for file I/O and they Must be declared before it can be used Must be initialized before it can contain valid data Initializing a stream means connecting it to a file The value of the stream variable is really the filename it is connected to Can have their values changed Changing a stream value means disconnecting from one file and then connecting to another 11/1/2017 Matni, CS16, Fa17 6

Streams and Assignment Streams use special built-in (member) functions instead of the assignment operator to change values Example: streamobjectx.open( addressbook.txt ); // connects to file streamobjectx.close(); // closes connection to file 11/1/2017 Matni, CS16, Fa17 7

Declaring An Input-File Stream Variable Input-file streams are of type ifstream Type ifstream is defined in the fstream library You must use include statement and using directives #include <fstream> using namespace std; Declare an input-file stream variable with: ifstream in_stream; Variable type Variable name 11/1/2017 Matni, CS16, Fa17 8

Declaring An Output-File Stream Variable Ouput-file streams of are type ofstream Type ofstream is defined in the fstream library Again, you must use the include and using directives #include <fstream> using namespace std; Declare an output-file stream variable using ofstream out_stream; Variable type Variable name 11/1/2017 Matni, CS16, Fa17 9

Connecting To A File Input Data File Your C++ Program Output Data File Once a stream variable is declared, you can connect it to a file Connecting a stream to a file means opening the file Use the open member function of the stream object 11/1/2017 in_stream.open("infile.dat"); Period Member function syntax Double quotes File name on the disk Must include a true path (relative or absolute)

Using The Input Stream Once connected to a file, get input from the file using the extraction operator (>>) Just like with cin Example: ifstream in_stream; in_stream.open( infile.dat ); int one_number, another_number; in_stream >> one_number >> another_number; The inputs are read from the infile.dat file separated by either spaces or newline characters in_stream.close(); 11/1/2017 Matni, CS16, Fa17 11

Using The Output Stream An output-stream works similarly using the insertion operator (<<) Just like with cout Example: ofstream out_stream; out_stream.open( outfile.dat ); The output gets written in the outfile.dat file out_stream << one number = << num1 <<, another number = << num2; out_stream.close(); 11/1/2017 Matni, CS16, Fa17 12

The External File Name Must be the name of a file that the operating system can use/open/read/write Be compliant with naming conventions on your system Example: Don t call an input **text** file XYZ.jpg Make sure the path is true If the file is local to your program, then no path is needed Otherwise use either relative or absolute path names Example: infile.open(../mydirectory/inputfile_42.txt ); 11/1/2017 Matni, CS16, Fa17 13

Closing a File After using a file, it should be closed using the.close() function This disconnects the stream from the file Close files to reduce the chance of a file being corrupted if the program terminates abnormally Example: in_stream.close(); It is important to close an output file if your program later needs to read input from the output file The system will automatically close files if you forget as long as your program ends normally! 11/1/2017 Matni, CS16, Fa17 14

Member Functions Member function: function associated with an object.open() is a member function of in_stream in the previous examples in_stream is an object of class ifstream Likewise, a different.open() is a member function of out_stream in the previous examples Despite having the same name! out_stream is an object of class ofstream For a list of member functions for I/O stream classes, also see: http://www.cplusplus.com/reference/fstream/ifstream/ http://www.cplusplus.com/reference/fstream/ofstream/ 11/1/2017 Matni, CS16, Fa17 15

Classes vs. Objects A class is a complex data type that can contain variables & functions Example: ifstream, ofstream, string are examples of C++ classes We ll discuss classes and objects in C++ later in the quarter When you call up a class to use it in a program, you instantiate it as an object Example: ifstream MyInputStream; // MyInputStream is an object of class ifstream 11/1/2017 Matni, CS16, Fa17 16

Calling a Member Function Calling a member function requires specifying the object containing the function The calling object is separated from the member function by the dot operator Example: in_stream.open("infile.dat"); Calling object Dot operator Member function 11/1/2017 Matni, CS16, Fa17 17

Errors On Opening Files Opening a file can fail for several reasons The file might not exist The name might be typed incorrectly Other reasons Caution: You may not see an error message if the call to open fails!! Program execution usually continues! 11/1/2017 Matni, CS16, Fa17 18

Catching Stream Errors Member function fail(), can be used to test the success of a stream operation fail() returns a Boolean type (True or False) fail() returns True (1) if the stream operation failed 11/1/2017 Matni, CS16, Fa17 19

Halting Execution When a stream open function fails, it is generally best to stop the program then and there! The function exit(), halts a program exit(n) returns its argument (n) to the operating system exit(n) causes program execution to stop exit(n) is NOT a member function! It s a function defined in cstdlib Exit requires the include and using directives #include <cstdlib> using namespace std; 11/1/2017 Matni, CS16, Fa17 20

Using fail and exit Immediately following the call to open, check that the operation was successful: in_stream.open("stuff.dat"); if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; } // You can also use cerr instead of cout exit(1); // Program quits right here! 11/1/2017 Matni, CS16, Fa17 21

A Note on cerr vs cout Use cout for the standard output. Use cerr to show errors. There is a difference in how the outputs are buffered or not. Has to do with how the memory is used: Not a scope of CS16 11/1/2017 Matni, CS16, Fa17 22

Formatting Output to Files Recall: Format output to the screen with: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Similarly, format output to a file using out_stream with: out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2); 11/1/2017 Matni, CS16, Fa17 23

11/1/2017 Matni, CS16, Fa17 24

Creating Space in Output The width member function specifies the number of spaces for the next item Applies only to the next item of output Example: To print the digit 7 in four spaces and use out_stream.width(4); out_stream << 7 << endl; Three of the spaces will be blank:.setf(ios::right) default 7 7.setf(ios::left) 11/1/2017 25

Not Enough Width? What if the argument for width is too small? Such as specifying cout.width(3); when the value to print is 3456.45 The entire item is always put in output If too few spaces are specified, then spaces are added as needed In the example above, the entire value (3456.45) is still printed out as if the cout.width(3); was not there. 11/1/2017 Matni, CS16, Fa17 26

Unsetting Flags Any flag that is set, may be unset Use the unsetf function Example: cout.unsetf(ios::showpos); causes the program to stop printing plus signs on positive numbers 11/1/2017 Matni, CS16, Fa17 27

Manipulators A type of function called in a nontraditional way Manipulators, in turn, call member functions May or may not have arguments to them Used after the insertion operator (<<) as if the manipulator function call is an output item 11/1/2017 Matni, CS16, Fa17 28

The setw Manipulator setw does the same task as member function width setw calls the width function to set spaces for output: only effective for one use Found in the library <iomanip> Example: cout << "Start" << setw(4) << 10 << setw(4) << 20 << setw(6) << 30; produces: Start 10 20 30 2 Spaces 4 Spaces The 1 st setw(4) ensures 4 spaces between Start" and 10, INCLUSIVE of the spaces taken up by 10. The 2 nd setw(4) ensures 4 spaces between 10 and 20, INCLUSIVE of the spaces taken up by 20. The 3 rd setw(6) ensures 6 spaces between 20 and 30, INCLUSIVE of the space taken up by 30. 11/1/2017 Matni, CS16, Fa17 29

The setprecision Manipulator setprecision does the same task as member function precision Found in the library <iomanip> Example: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "$" << setprecision(2) << 10.3 << endl << "$" << 20.5 << endl; produces: $10.30 $20.50 setprecision setting stays in effect until changed 11/1/2017 Matni, CS16, Fa17 30

Appending Data to Output Files Output examples we ve given so far create new files If the output file already contained data, that data is now lost! To append new output to the end an existing file use the constant ios::app defined in the iostream library: outstream.open("important.txt", ios::app); If the file does not exist, a new file will be created There are other member functions that return the location in the I/O file where the next data will be Helps with customizing read and writing files To be used carefully! We won t go over them here 11/1/2017 Matni, CS16, Fa17 31

Entering File Names for I/O Files Users can also enter the name of a file to be read/written As an input read by cin You can use regular C++ strings for the filenames, but ONLY if you ensure that you are compiling with C++ version 11 (or later). OTHERWISE, you ll have to use C-strings WARNING!!!! PAY ATTENTION TO THIS!!! Textbook has details on how to use C-strings for filenames 11/1/2017 Matni, CS16, Fa17 32

More Options for Compilations Using g++ So far, you ve been using g++ as follows: g++ mylittleprog.cpp o mylittleprog You can tell g++ to also make sure that it uses ver. 11: g++ mylittleprog.cpp o mylittleprog std=c++11 Additionally, g++ can also print out warnings for you, not just compile errors (this can help you in catching problems early!) g++ mylittleprog.cpp o mylittleprog std=c++11 -Wall 11/1/2017 Matni, CS16, Fa17 33

YOUR TO-DOs HW 5 due Thu. 11/2 Lab 5 due Fri. 10/27 Visit Prof s and TAs office hours if you need help! Call Mom 11/1/2017 Matni, CS16, Fa17 34

11/1/2017 Matni, CS16, Fa17 35