Input and Output File (Files and Stream )

Similar documents
BITG 1113: Files and Stream LECTURE 10

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

Chapter 14 Sequential Access Files

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

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

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

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

System Design and Programming II

Objects and streams and files CS427: Elements of Software Engineering

Lecture 3 The character, string data Types Files

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

C++ Programming Lecture 10 File Processing

Week 5: Files and Streams

Chapte t r r 9

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

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

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

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

Simple File I/O.

Fundamental File Processing Operations 2. Fundamental File Processing Operations

EP241 Computing Programming

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

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

C++ files and streams. Lec 28-31

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

Chapter 3 - Notes Input/Output

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

Unit-V File operations

Advanced I/O Concepts

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

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

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

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

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

Scientific Computing

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

File handling Basics. Lecture 7

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

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

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

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

IS 0020 Program Design and Software Tools

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

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

C++ Input/Output: Streams

Chapter 12: Advanced File Operations

Chapter-12 DATA FILE HANDLING

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

PROGRAMMING EXAMPLE: Checking Account Balance

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

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

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

Developed By : Ms. K. M. Sanghavi

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

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

Streams contd. Text: Chapter12, Big C++

Lecture 9. Introduction

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

Object Oriented Programming In C++

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

Chapter 12. Streams and File I/O

Fundamentals of Programming Session 25

CS101 Linux Shell Handout

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

Writing a Good Program. 7. Stream I/O

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

Fall 2017 CISC/CMPE320 9/27/2017

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

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

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

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

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

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

More File IO. CIS 15 : Spring 2007

C++ Input/Output Chapter 4 Topics

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

Object-Oriented Programming in C++

COMP322 - Introduction to C++

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

Lab: Supplying Inputs to Programs

Fundamentals of Programming Session 27

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

ios ifstream fstream

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

Chapter 3: Input/Output

COMP322 - Introduction to C++

A SHORT COURSE ON C++

This can be thrown by dynamic_cast. This is useful device to handle unexpected exceptions in a C++ program

Study Material for Class XII. Data File Handling

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*...

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 11: Records (structs)

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

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

C++ Quick Guide. Advertisements

CS Programming2 1 st Semester H Sheet # 8 File Processing. Princess Nora University College of Computer and Information Sciences

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Random File Access. 1. Random File Access

Chapter 1 INTRODUCTION

Transcription:

Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14

Scope Describe the fundamentals of input & output files. Use data files for input & output purposes.

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.

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.

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).

What are the steps needed to Use Files? Include the <fstream> header file Define a file stream object using appropriate file stream class Open the file Use the file Close the file

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. 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

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 );

Input / Output : File Name vs File Stream Object

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

Open File Modes There are a few modes to open a file. They are listed as follows: Mode and 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

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);

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 More on Open File Mode 13

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;

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.

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;

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.

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.close(); return 0; } datafile << setw(10)<<id<<setw(20)<<name<<setw(5)<<m1<<setw(5)<<m2<<endl;

For example the input of the program is entered as follows :

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:

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"); 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; }

Example 2 #include <iostream> #include <fstream> #include <cstring> using namespace std; 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 << line << endl; } } cout<<endl; myfile.close(); else cout << "Unable to open file"; return 0; }