C++ Programming Lecture 10 File Processing

Similar documents
IS 0020 Program Design and Software Tools

Fundamentals of Programming Session 27

Lecture 9. Introduction

Chapter 8 File Processing

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

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

C++ files and streams. Lec 28-31

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

Object Oriented Programming In C++

by Pearson Education, Inc. All Rights Reserved. 2

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

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

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

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

Random File Access. 1. Random File Access

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

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

Chapter-12 DATA FILE HANDLING

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

Fundamentals of Programming Session 25

Chapter 3 - Notes Input/Output

Unit-V File operations

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

System Design and Programming II

Chapter 12: Advanced File Operations

Fall 2017 CISC/CMPE320 9/27/2017

Advanced I/O Concepts

Fundamentals of Programming Session 28

BITG 1113: Files and Stream LECTURE 10

Input and Output File (Files and Stream )

Chapte t r r 9

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

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

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

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

UNIT V FILE HANDLING

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

Chapter 14 Sequential Access Files

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

ios ifstream fstream

COMP322 - Introduction to C++

Developed By : Ms. K. M. Sanghavi

Objects and streams and files CS427: Elements of Software Engineering

Streams contd. Text: Chapter12, Big C++

Module 11 The C++ I/O System

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

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

C++ Input/Output: Streams

Streams - Object input and output in C++

Fundamental File Processing Operations 2. Fundamental File Processing Operations

EP241 Computing Programming

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

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

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Object Oriented Programming CS250

Writing a Good Program. 7. Stream I/O

Input/Output Streams: Customizing

Lecture 3 The character, string data Types Files

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() {

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

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

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

Study Material for Class XII. Data File Handling

by Pearson Education, Inc. All Rights Reserved. 2

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

COMP322 - Introduction to C++

Object Oriented Programming

Chapter 14 File Processing

C++ How to Program 14.6

PROGRAMMING EXAMPLE: Checking Account Balance

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

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

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

Generate error the C++ way

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

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

by Pearson Education, Inc. All Rights Reserved. 2

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

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

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

Fig: iostream class hierarchy

File handling Basics. Lecture 7

Lecture 5 Files and Streams

Lecture6 File Processing

10/23/02 21:20:33 IO_Examples

CS201 Solved MCQs.

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

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

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-

C++ Input/Output Chapter 4 Topics

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

Introduction to C++ (Extensions to C)

What we will learn about this week:

Introduction. Lecture 5 Files and Streams FILE * FILE *

Expressions, Input, Output and Data Type Conversions

Chapter 3: Input/Output

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

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

Software Design & Programming I

Transcription:

C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department

Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential Access File. Reading Data from a Sequential Access File. Updating Sequential Access Files. Input/Output Manipulations. Examples. The Hashemite University ٢

Introduction Data files can be created, updated, and processed by C++ programs Files are used for permanent storage of large amounts of data Storage of data in variables and arrays is only temporary The Hashemite University ٣

The Data Hierarchy I Bit - smallest data item value of 0 or 1 Byte 8 bits used to store a character Decimal digits, letters, and special symbols Field - group of characters conveying meaning Example: your name Record group of related fields Represented as a struct or a class Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc. File group of related records Example: payroll file Database group of related files The Hashemite University ٤

The Data Hierarchy II Sally Black Tom Blue Judy Green Iris Orange Randy Red File Judy Judy 01001010 Green Field Byte (ASCII character J) Record Record key 1 Bit identifies a record to facilitate the retrieval of specific records from a file Sequential file records typically sorted by key The Hashemite University ٥

Files and Streams C++ views each file as a sequence of bytes File ends with the end-of-file marker Stream is created when a file is opened File processing Headers <iostream> and <fstream> class ifstream - input class ofstream - output class fstream - either input or output The Hashemite University ٦

Creating a Sequential Access File Files are opened by creating objects of stream classes ifstream, ofstream or fstream Makes a "line of File stream member functions for object file: communication" with the object and file.open( Filename, fileopenmode); the file. file.close(); closes file File open modes: Mode ios::app ios::ate ios::in ios::out ios::trunc ios::binary Description Write all output to the end of the file. Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file. Open a file for input. Open a file for output. Discard the file s contents if it exists (this is also the default action for ios::out) Open a file for binary (i.e., non-text) input or output. The Hashemite University ٧

Example I #include<iostream> #include<fstream> using namespace std; int main() { ofstream out_file("hu.txt", ios::out); //or HU.dat if(out_file == 0) { cout <<"Unable to open the file\n"; exit(1); } for(int i = 0; i < 9; i++) out_file << i << endl; out_file.close(); } return 0; The Hashemite University ٨

Example II Storing Data Entered By the User #include<iostream> #include<fstream> using namespace std; int main() { ofstream out_file("hu.txt", ios::in); //or HU.dat int a; if(out_file == 0) { cout <<"Unable to open the file\n"; exit(1); } while(a!= -1) //end when -1 is entered { out_file << a << endl; cout <<"Enter an integer to save on file\n"; cin >> a; } } out_file.close(); return 0; cout <<"Enter an integer to save on file\n"; cin >> a; The Hashemite University ٩

Notes You will find the created text file in the same directory in which you save the source code unless you specify the full path of where you want to save the created text file. The extension of the created file could be.txt or.dat Pay attention to how the data is written on the file (wether there are formatted, only one value is stored per line or multiple ones, etc.) to read the data correctly. All attributes associated with cin object (stopping at enetr or white spaces, read vales based on the data type of the holder, etc.) are applied to files reading. ofstream are opened for output by default.so, in the previous example writing ofstream out_file("hu.txt"); is the same as ofstream out_file("hu.txt", ios::out); The Hashemite University ١٠

Reading Data from a Sequential Access File File stream member functions for repositioning file position pointer: seekg (seek get) for istream and seekp (seek put) for ostream // position to the nth byte of fileobject // assumes ios::beg fileobject.seekg( n ); // position n bytes forward in fileobject fileobject.seekg( n, ios::cur ); // position y bytes back from end of fileobject fileobject.seekg( y, ios::end ); // position at end of fileobject fileobject.seekg( 0, ios::end ); tellg and tellp return current location of pointer location = fileobject.tellg() //returns long int The Hashemite University ١١

Example #include<iostream> #include<fstream> using namespace std; int main() { ifstream in_file("hu.txt", ios::in); //or HU.dat int a; if(in_file == 0) { cout <<"Unable to open the file\n"; exit(1); } for(int i = 0; i < 9; i++) { in_file >> a; cout << a << endl; } } in_file.close(); return 0; The Hashemite University ١٢

Example Output The Hashemite University ١٣

Note The file that you read from must be stored in the same directory in which you store the source code file, otherwise you must specify the full path of where you store the file. The extension of the created file could be.txt or.dat ifstream are opened for input by default. so, in the previous example writing ifstream in_file("hu.txt"); is the same as ifstream in_file("hu.txt", ios::in); The Hashemite University ١٤

Updating Sequential Access Files Sequential access file Cannot be modified without the risk of destroying other data 300 White 0.00 400 Jones 32.87 (old data in file) if we want to change White's name to Worthington, 300 Worthington 0.00 300 White 0.00 400 Jones 32.87 300 Worthington 0.00ones 32.87 Data gets overwritten Formatted text which is output to a file is very different than the internal representation The Hashemite University ١٥

Input/Output Manipulations C++ provides various stream manipulators that perform formatting tasks. Till now we have dealt with screen output using cout. So, all these manipulators will format the text that appears on the screen. Examples: Setting the precision of the displayed floating point numbers. Setting the field width. Showing trailing zeros and decimal point in floating point numbers. Filling field with specific characters. The Hashemite University ١٦

Floating-Point Precision (setprecision) setprecision sets number of digits to the right of decimal point (with rounding) parameterized stream manipulator Like all parameterized stream manipulators, <iomanip> required specify precision: cout << setprecision(2) << x; Changes last until a different value is set. The Hashemite University ١٧

Field Width(setw) setw stream manipulator sets field width (number of character positions a value should be output or number of characters that should be input). returns to previous width after the implementation (so it is applied to the next insertion or extraction only). If values processed are smaller than width, fill characters inserted as padding. Large values are not truncated - full number printed. Displayed output is right justified. Examples: cin >> setw(5) >> number; cout << setw(5) << number; The Hashemite University ١٨

Trailing Zeros and Decimal Points (showpoint) ios::showpoint forces a float with an integer value to be printed with its decimal point and trailing zeros cout << showpoint << 79.0; will print 79.00000 number of zeros determined by precision settings Applied for all subsequent output operations. To reset this option apply the following command: cout << noshowpoint; Remember trailing zeros are applied to floating point numbers only and not for integers. The Hashemite University ١٩

Padding (setfill) If you specify the field width to 10 and you print 56 then this number will be preceded by white spaces. White space here is the fill character. You can change this fill character to any other character you want. Applied for all subsequent cout statements. To remove it set the fill character to white space to return to the default settings. setfill manipulator sets fill character cout << setfill ('*'); cout << setw(5) << 3; //output is ****3 The Hashemite University ٢٠

Floating-Point Numbers; Scientific Notation (scientific, fixed) scientific forces output of a floating point number in scientific notation: 1.946000e+009 Only one digit in the integer part of the floating point number and n digits after the floating point (depends on the precision value) and put the suitable power after the e exponent. E.g.: cout << scientific << 234.5678; fixed forces floating point numbers to display a specific number of digits to the right of the decimal (specified with precision) and the whole integral part. E.g.: cout << fixed << 234.5e-1; Applied for all subsequent cout statements. The default setting in C++ is the fixed formatting or depends on the original value of the floating point number. The Hashemite University ٢١

Additional Notes This lecture covers the following material from the textbook: Chapter 14: Sections 14.1 14.6 Chapter 12: Sub-Sections 12.6.2, 12.6.3, 12.7.1, 12.7.3, 12.7.5 This is the last lecture included in the first exam material. The Hashemite University ٢٢