BITG 1113: Files and Stream LECTURE 10

Similar documents
Input and Output File (Files and Stream )

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

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

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

Objects and streams and files CS427: Elements of Software Engineering

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

Week 5: Files and Streams

Chapter 14 Sequential Access Files

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

C++ Programming Lecture 10 File Processing

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

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

Lecture 3 The character, string data Types Files

System Design and Programming II

C++ files and streams. Lec 28-31

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

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

Simple File I/O.

Chapter 5: Loops and Files

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

Chapte t r r 9

File handling Basics. Lecture 7

IS 0020 Program Design and Software Tools

Object-Oriented Programming in C++

Fundamental File Processing Operations 2. Fundamental File Processing Operations

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

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

Files Total: // Files Example 1. #include <iostream> #include <fstream>

3.1. Chapter 3: Displaying a Prompt. Expressions and Interactivity

Lecture 9. Introduction

Unit-V File operations

EP241 Computing Programming

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

Scientific Computing

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

Chapter 3 - Notes Input/Output

Advanced I/O Concepts

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

Fundamentals of Programming Session 25

Lecture 14. Xiaoguang Wang. March 11th, 2014 STAT 598W. (STAT 598W) Lecture 14 1 / 36

Object Oriented Programming In 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.

PROGRAMMING EXAMPLE: Checking Account Balance

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

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

SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) which generates a random number in the range of 0 to n-1. For example;

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

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

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

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

CS101 Linux Shell Handout

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

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

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

for (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;

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

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

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

A SHORT COURSE ON C++

Fundamentals of Programming Session 27

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

Lecture 5 Files and Streams

C++ Input/Output: Streams

Chapter 12. Streams and File I/O

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

Developed By : Ms. K. M. Sanghavi

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

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

C Legacy Code Topics. Objectives. In this appendix you ll:

Fall 2017 CISC/CMPE320 9/27/2017

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

Class Example. student.h file: Declaration of the student template. #ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED

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

Chapter-12 DATA FILE HANDLING

Chapter 12: Advanced File Operations

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

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

Streams contd. Text: Chapter12, Big C++

Introduction. Lecture 5 Files and Streams FILE * FILE *

Sample Code: OUTPUT Daily Highs & Lows

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

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

COMP322 - Introduction to C++

COMP322 - Introduction to C++

Chapter 8 File Processing

BITG 1113: Array (Part 2) LECTURE 9

BITG 1113: Function (Part 2) LECTURE 5

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

Preview 8/28/2018. Review for COSC 120 (File Processing: Reading Data From a File)

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

CS 103 Unit 14 - Streams

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

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

CSCE 206: Structured Programming in C++

Summary of basic C++-commands

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

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

Writing a Good Program. 7. Stream I/O

CS 103 Unit 14 - Streams

Random File Access. 1. Random File Access

Transcription:

BITG 1113: Files and Stream LECTURE 10 1

LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output purposes. 2

Files Normally, it is difficult to handle large amounts of input data and output data and would always be lost as soon as we turned off the computer. We can use a file instead of keyboard for program input. The file is called input file. We can use a file instead of monitor screen for program output. The file is called output file. File a collection of related data usually stored in secondary storage devices such as Disk, Tape, etc. Purpose to keep data in a secondary storage. 3

Files Using file, data can be created by one program, stored (or saved) on secondary devices, and then accessed or modified by other programs when necessary. Two major characteristics of files are: Text files : data in text format Binary files : data in binary format Files in a secondary storage can be both read and written. These processes are also known as input/output. 4

Types of File Stream The type of stream class determines if it is an input file or an output file or both. ofstream output file stream class. Creating files and writing data to them (output file). ifstream input file stream class. Opening existing and reading data from them into memory (input file). fstream file stream class. Creating files, writing data to them and reading data from them (both input & output file). 5

What are the steps needed to Use Files? 1) Include the <fstream> header file 2) Define a file stream object using appropriate file stream class 3) Open the file 4) Use the file 5) Close the file 6

(1)- Include the <fstream> header file Standard input stream (cin) and standard output stream (cout) requires the <iostream> header file. File input/output stream both requires <fstream> header file. (2) - Define a file stream object using appropriate file stream class ( ifstream / ofstream / fstream ) A file is identified by its file name, e.g. student.dat Inside a C++ program, a file is identified by a file stream object. eg: ifstream infile; // infile is an input file stream // object, with ifstream class eg: ofstream outfile;// outfile is an output file // stream object, with ofstream class 7

(3) - Opening a File : input / output file The object is then linked to the actual file as follows: infile.open( student.dat ); outfile.open( student_new.dat ); ***Alternative : statements found in (2) & (3) could be combined as the following statements: ifstream infile( student.dat ); ofstream outfile( student_new.dat ); 8

Input / Output : File Name vs File Stream Object infile student.dat student_new.dat outfile Memory ifstream infile( student.dat ); ofstream outfile( student_new.dat ); 9

File Name Example: ifstream myinputfile; char filename[20]; OR cout << Enter name of the data file: ; cin >> filename; myinputfile.open(filename); char filename[20]; cout << Enter name of the data file: ; cin >> filename; ifstream infile(filename); 10

Open File Modes There are a few modes to open a file. They are listed as follows: Mode Description ios::in Input mode. Data will be read from the file. The file MUST exists. If the file doesn t exist, it will not be created and the open function fails. ios::out Output mode. Data will be written to the file. The file will be created if it does not exist. If it already exists, the file s content will be deleted and replaced by the new data. ios::app Append mode. If the file already exists, its contents are preserved and all output is written to the end of the file. If the file doesn t exist, it will be created. 11

More on Open File Mode All these modes can be combined using the operator (which means OR). For example, if we want to open the file example.bin to add data we could do it by the following statement : ofstream myfile("example.bin", ios::out ios::app); 12

More on Open File Mode For all file stream classes, default mode/s is/are automatically applied if the file is opened without specifying any value for the mode parameter. Stream class Default mode parameter ofstream ios::out ifstream ios::in fstream ios::in ios::out 13

(4) - Use the file Can use output file stream object and << to send data to a file outfile << "Inventory report"; Can use input file stream object and >> to copy data from file to variables infile >> partnum; infile >> qtyinstock >> qtyonorder; 14

(5) - Closing a File When we are finished with our input and output operations on a file we should close it. When a file is closed, any unsaved data in the buffer will be saved to its file. Closing a file improves system s performance (the operating system s resources is better utilized.) Use the close member function infile.close(); outfile.close(); After closing a file, the file stream object (above eg: infile and outfile) can be used again to open another file. 15

Example of Output File Writing output to a text file : Example 1 # include <iostream> # include <fstream> using namespace std; int main() { double income = 123.45, expenses = 987.65; int week = 7, year = 2006; ofstream outfile("l4_2.out");// default mode is ios::out outfile<<"week = "<<week<<endl<<"year = "<<year<<endl; outfile<<"income = "<<income<<endl<<"expenses = "<<expenses<<endl; outfile.close(); return 0; 16

Example of Output File: More on Example 1 Content of L4_2.out text file : You can find the L4_2.out file in the same folder as the C++ program that wrote the file. Open it using the notepad. 17

Example of Output File Writing output to a text file : Example 2 #include <iostream> #include <iomanip> #include <fstream> using namespace std; int main () { char name[20]; char id[10]; float m1,m2; ofstream datafile ( student.txt", ios::out); cout<<"enter student's id, name, first mark and second mark."; cout<<"\npress <ctrl> + z to stop.\n"; while (cin >> id >> name >> m1 >> m2) //reading from keyboard using EOF while loop { datafile << setw(10)<<id<<setw(20)<<name<<setw(5)<<m1<<setw(5)<<m2<<endl; datafile.close(); return 0; 18

Example of Output File : More on Example 2 For example the input of the program is entered as follows : 19

Example of Output File : More on Example 2 Content of student.txt text file : You can find the student.txt file in the same folder as the C++ program that wrote the file. Open it using the notepad. 20

Input Files Input files can be also created using any text editor. Notepad is an example of text editor you can use to save your data. To create an input file using a text editor, open the notepad and type the data. Save the file in the same folder with the C++ program that will use these data. Example of the file is shown below: Save the file as : L4_3A.dat 21

Input File Reading data from a text file: Example 1 #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { double x; int i,j; ifstream infile1("l4_3a.dat"); ifstream infile2("l4_3b.dat"); Content of L4_3A.dat file: Content of L4_3B.dat file : infile1>>i>>j>>x; infile1.close(); cout<<"from first file i = "<<i<<", j = "<<j<<", x = "<<x<<endl; infile2>>i>>j>>x; infile2.close(); cout<<"from second file i = "<<i<<", j = "<<j<<", x = "<<x<<endl; return 0; Output displayed : 22

Input File Reading data from a text file: Example 2 #include <iostream> #include <fstream> #include <cstring> using namespace std; Content of example.txt text file : int main () { char line[50]; ifstream myfile ("example.txt"); if (myfile.is_open()) //checking file existance { while (! myfile.eof() ) // checking EOF for myfile using while loop { myfile.getline (line,50); //read string from myfile cout<<endl; cout << line << endl; myfile.close(); else cout << "Unable to open file"; return 0; Output displayed : 23

Input File Reading data from a text file: Example 2 (another solution) #include <iostream> #include <fstream> using namespace std; int main () { char line[50]; ifstream myfile ("example.txt",ios::in); if (!myfile) // if myfile exists, myfile expression is TRUE { cout << "Unable to open file"; exit(1); else { while (myfile.getline (line,50)) // reading string from myfile using EOF // while loop cout << line << endl; cout<<endl; myfile.close(); return 0; //write output to monitor 24

Input File Reading data from a text file: Example 3 #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main () { char name[20]; char id[10]; float m1,m2; Content of student.txt text file : ifstream datafile ( student.txt", ios::in); if (!datafile) // if datafile exists, datafile expression is TRUE { cout << "Unable to open file"; exit(1); while (datafile >> id >> name >> m1 >> m2) //read from datafile using EOF while loop { cout << setw(10)<<id<<setw(20)<<name<<setw(5)<<m1<<setw(5)<<m2<<endl; datafile.close(); return 0; Output displayed : 25

Example: Writing Data to a File #include<iostream> #include<fstream> using namespace std; int main() { ofstream myoutputfile; // declaring output file object myoutputfile.open( student_new.dat ); // file created in // the same directory as the program myoutputfile << Zulkarnain\n ; myoutputfile << Zulkifli\n ; myoutputfile << Zulmasri\n ; myoutputfile.close(); return 0; 26

Example: Reading Data From a File #include <iostream> #include <fstream> using namespace std; int main() { ifstream myinputfile; // declaring input file object char name[50]; myinputfile.open( student_new.dat ); // file will be // created in the same directory as the program myinputfile >> name; cout << name << endl; myinputfile >> name; cout << name << endl; myinputfile >> name; cout << name << endl; myinputfile.close(); return 0; 27

28

#include <fstream> #include <iostream> #include <cstdlib> // is required to use exit() #include <iomanip> using namespace std; int main() { char time[5]; double temperature; ifstream infile("temperature.txt",ios::in); ofstream outfile("temperature_revised.txt",ios::out); if (!infile) // check existence of input file { cout << "File could not be opened for input\n"; exit(1); outfile<<"* Revised Temperature * \n\n"; while (!infile.eof()) // checking end of file { infile >>time>>temperature; outfile<<time<<" "<<temperature * 5/9 <<'\n'; infile.close(); outfile.close(); return 0; 29

30

Open the input file ifstream infile; infile.open( clients.txt",ios::in); OR ifstream infile( clients.txt",ios::in); Open the output file ofstream outfile; outfile.open("output.txt",ios::out); OR ofstream outfile("output.txt",ios::out); Append the output file ofstream outfile; outfile.open("output.txt",ios::app); OR ofstream outfile("output.txt",ios::app); 31

Passing File Stream Objects to Functions #include <iostream> #include <fstream> using namespace std; const int SIZE = 5; // maximum size of character void showcontent (ifstream&); // function prototype int main() { ifstream infile; infile.open("temperature.txt"); if (!infile ) // check existence of input file { cout << endl << "Error in opening file..." << endl; exit(1); // exit program // if cout << "File opened successfully.\n"; cout << "Reading file contents...\n\n"; showcontent (infile); infile.close(); cout << "\ntask completed.\n\n"; return 0; // ================================================== end main 32

void showcontent (ifstream &infileobj) { char time[size]; double temperature; while (!infileobj.eof()) // checking end of file { infileobj >> time >> temperature; // read content cout << time << " " << temperature << endl; // display content // ============================================= end showcontent - END - 33