Simple File I/O.

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

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 #9

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

What we will learn about this week:

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

Chapter 12. Streams and File I/O

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.

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

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

Chapter 14 Sequential Access Files

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

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

Programming in C/C

Input and Output File (Files and Stream )

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

BITG 1113: Files and Stream LECTURE 10

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

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

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

Why Is Repetition Needed?

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

Programming in C/C

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

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

Week 5: Files and Streams

Chapte t r r 9

C++ Input/Output: Streams

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

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

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

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

Unit-V File operations

Understanding main() function Input/Output Streams

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

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

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.

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

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

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

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

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

Setting Justification

Lecture 3 The character, string data Types Files

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

Scientific Computing

Lecture 5 Files and Streams

2. It is possible for a structure variable to be a member of another structure variable.

PROGRAMMING EXAMPLE: Checking Account Balance

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Objects and streams and files CS427: Elements of Software Engineering

CSCI 1061U Programming Workshop 2. C++ Basics

A SHORT COURSE ON C++

C++ Input/Output Chapter 4 Topics

C++ for Python Programmers

Computer Programming : C++

C++_ MARKS 40 MIN

CS101 Linux Shell Handout

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

Chapter 5: Loops and Files

COMP322 - Introduction to C++

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

CS103L SPRING 2018 UNIT 7: FILE I/O

C++ For Science and Engineering Lecture 12

CMPS 221 Sample Final

Ch 6-2. File Input / Output

Writing a Good Program. 7. Stream I/O

Name Section: M/W T/TH Number Definition Matching (8 Points)

Your first C++ program

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

Introduction. Lecture 5 Files and Streams FILE * FILE *

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

Object Oriented Programming In C++

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:

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

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

Chapter 3: Input/Output

Chapter 3 - Notes Input/Output

Chapter 2. Flow of Control. Copyright 2016 Pearson, Inc. All rights reserved.

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

G52CPP C++ Programming Lecture 17

Fundamentals of Programming Session 25

CS11 Intro C++ Spring 2018 Lecture 3

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

C++ STREAMS; INHERITANCE AS

Streams contd. Text: Chapter12, Big C++

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

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

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

Lab: Supplying Inputs to Programs

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

Fundamentals of Programming CS-110. Lecture 2

Name Section: M/W T/TH Number Definition Matching (6 Points)

Transcription:

Simple File I/O from Chapter 6 http://www.cplusplus.com/reference/fstream/ifstream/ l / /f /if / http://www.cplusplus.com/reference/fstream/ofstream/

I/O Streams I/O refers to a program s input and output Input is delivered to a program via a stream Input can be from: the keyboard or a file Output is delivered to an output device via a stream Output can be: the screen, or a file

Streams and Basic File I/O A stream is a flow of data. Input stream: data flows into the program If input stream flows from keyboard, the program will accept data from the keyboard If input stream flows from a file, the program will accept data from the file Output stream: data flows out of the program To the screen To a file

cin And cout Streams cin input stream connected to the keyboard cout output stream connected to the screen cin and cout defined in the iostream library Use include directive: #include <iostream> We can declare our own streams to use with files.

Why Use Files? Files allow you to store data permanently! Data output to a file lasts after the program ends A file can be used for input over and over No typing of data again and again for testing Create a data file or write into an output file at your convenience Files allow you to deal with larger data sets

File I/O Reading from a file Taking input from a file From beginning g to the end (for now) Just as done from the keyboard Writing to a file Sending output to a file From beginning to end (for now) Just as done to the screen

Stream Variables or Objects We use a stream variable or object for file I/O It must be declared before it can be used It must be initialized before it contains valid data Initializing i a stream means connecting it to a file The value of the stream variable can be thought of as the file it is connected to Can have its value changed Changing a stream value means disconnecting from one file and connecting to another

Declaring An Input-file Stream Variable Input-file streams are of type ifstream Type ifstream is defined in the fstream library You must use the include and using directives #include <fstream> using namespace std; Declare an input-file stream variable or object ifstream in_stream;

Declaring An Output-file Stream Variable Ouput-file streams of are type ofstream Type ofstream is defined in the fstream library You must use these include and using directives #include <fstream> using namespace std; Declare an output-file stream variable using ofstream out_stream;

Connecting To A File Once a stream variable or object is declared, we can connect it to a file Connecting a stream to a file is opening the file Use the open function of the stream object ifstream in_stream; in_stream.open("infile.dat"); File name on the disk

External File Names An External File Name Is the "real", on-the-disk, name for a file Is the name for a file that the operating system uses infile.dat used in the previous example Needs to match the naming conventions on your system Usually only used in a stream's open statement Once opened (i.e., connected to a stream object), it is referred to using the name of the stream connected to it.

Using The Input Stream Once connected to a file, the input-stream variable can be used to produce input just as you would use cin with the extraction operator Example: ifstream in_stream; in_stream.open("infile.dat"); int one_number, another_number; in_stream >> one_number >> another_number;

Intro to objects and classes 1

Objects An object is a variable that has member functions as well as the ability to hold data values instream and outstream each have a function named open associated with them instream and outstream use different versions of a function named open One version of open is for input files A different version of open is for output files string str; str is an object str.length() calling member function length() on str obj Class: a data type whose variables are objects so far, we have seen classes: string, ifstream, Class vs. native data type Slide 6-20

Member Functions A member function is a function associated with an object The open function is a member function of instream in the previous examples A different open function is a member function of outstream in the previous examples Slide 6-21

Objects and 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 string str1, str2; http://www.cplusplus.com/reference/string/ string/ Slide 6-22

Classes A type whose variables are objects, is a class ifstream is the type of instream variable (object) ifstream is a class The class (type) of an object determines its member functions Example: ifstream instream1, instream2; instream1.open and instream2.open are the same function but might have different arguments Slide 6-23

Class Member Functions 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 Every variable (object) declared of type ifstream has that open function Slide 6-24

Calling a Member Function Calling a member function requires specifying on which object the function is being called The calling object is separated from the member function by the dot operator Example: instream.open( infile.dat"); Dot operator Calling object Member function e.g, string str= Hello! World ; to find the length of str: str.length(); Slide 6-25

Member Function Calling Syntax Syntax for calling a member function: Calling_object.Member_Function_Name(Argument_list); Slide 6-26

Using The Output Stream An output-stream works similarly to the input-stream ofstream out_stream; out_stream.open("outfile.dat"); ") out_stream << "one number = " << one_number << "another number = " << another_number;

Closing a File After using a file, it should be closed This disconnects the stream from the file Close files to reduce the chance of a file being corrupted if the program terminates abnormally 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 Good practice: always close a file immediately after your code has used it. Display 6.1

Errors On Opening Files Opening a file could fail for several reasons Common reasons The file might not exist The name might be typed incorrectly May be no error message if the call to open fails Program execution continues!

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 if the stream operation fail returns true if the stream operation failed

Halting Execution When a stream open function fails, it is generally best to stop the program The function exit, halts a program exit returns its argument to the operating system exit causes program execution to stop exit is NOT a member function Exit requires the include and using directives #include <cstdlib> using namespace std;

Using fail and exit Immediately following the call to open, check that the operation was successful: in_stream.open("stuff.dat"); t t") if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1) ; } Display 6.2

Techniques for File I/O When reading input from a file Do not include prompts or echo the input The lines cout << "Enter the number: "; cin >> the_number; cout << "The number you entered is " << the_number; become just one line in_file >> the_number; The input file must contain exactly the data expected

Appending Data Output examples so far create new files ofstream out_stream; out_stream.open("outfile.dat"); If the output file already contains data, that data is 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 Display 6.3

Using File Name char file_name[16]; cout << "Enter the file_name "; cin >> file_name; ifstream in_stream; in_stream.open(file_name); Display 6.4 (1) if (in_stream.fail( ) ) Display 6.4 (2) { cout << "Input file opening failed.\n"; exit(1); } A program can ask the user to enter the name of a file to use for input or for output Program can use a string variable for a file s name

Detecting The End of The File Input files used by a program may vary in length Programs may not be able to assume the number of items in the file How to know the end of the file is reached? The expression in_stream >> next Reads a value from in_stream and stores it in next Returns true if a value can be read and stored in next Returns false if there is not a value to be read (the end of the file)

Detecting The End of File Example To calculate the average of the numbers in a file double next, sum = 0; int count = 0; while(in_stream >> next) { sum = sum + next; count++; } double average = sum / count;

Detecting the End of a File Member function eof (of every input-file stream) detects the end of a file eof stands for end of file eof returns a boolean value true when the end of the file has been reached false when there is more data to read Normally used to determine when we are NOT at the end of the file Example: if (! in_stream.eof( ) )

Using eof This loop reads each character, and writes it to the screen in_stream.get(next); while (! in_stream.eof( ) ) { cout << next; in_stream.get(next); } (! I t f( ) ) b f l h th (! In_stream.eof( ) ) becomes false when the program reads past the last character in the file

The End Of File Character End of a file is indicated by a special character in_stream.eof( ) is still false after the last character of data is read in_stream.eof( ) becomes true when the special end of file character is read