ios ifstream fstream

Similar documents
Unit-V File operations

Chapter-12 DATA FILE HANDLING

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

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

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

Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on

Chapte t r r 9

C++ Programming Lecture 10 File Processing

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

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

Study Material for Class XII. Data File Handling

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.

IS 0020 Program Design and Software Tools

C++ files and streams. Lec 28-31

Random File Access. 1. Random File Access

DISK FILE PROGRAM. ios. ofstream

Downloaded from

Developed By : Ms. K. M. Sanghavi

Chapter 14 Sequential Access Files

by Pearson Education, Inc. All Rights Reserved. 2

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

Fall 2017 CISC/CMPE320 9/27/2017

Lecture 9. Introduction

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

Page 1

Advanced I/O Concepts

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

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

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

C++ How to Program 14.6

File handling Basics. Lecture 7

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


Chapter 8 File Processing

Stream States. Formatted I/O

Input and Output File (Files and Stream )

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

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

Writing a Good Program. 7. Stream I/O

Module 11 The C++ I/O System

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

Input/Output Streams: Customizing

Object Oriented Programming CS250

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

SUBMITTED AS A PART OF C.B.S.E. CURRICULUM FOR THE YEAR

Lecture 5 Files and Streams

Fundamentals of Programming Session 27

Streams contd. Text: Chapter12, Big C++

Chapter 3 - Notes Input/Output

Chapter 12: Advanced File Operations

by Pearson Education, Inc. All Rights Reserved. 2

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

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

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

Applications with Files, Templates

COMP322 - Introduction to C++

BITG 1113: Files and Stream LECTURE 10

Introduction. Lecture 5 Files and Streams FILE * FILE *

DE122/DC106 Object Oriented Programming with C++ DEC 2014

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

(1)Given a binary file PHONE.DAT, containing records of the following structure type class Phonlist { char Name[20]; char Address[30]; char

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

AC55/AT55 OBJECT ORIENTED PROGRAMMING WITH C++ DEC 2013

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

Computer Science, Class XII, Chapter No.7 (Data File Handling)

More File IO. CIS 15 : Spring 2007

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

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

UNIT V FILE HANDLING

All About: File I/O in C++ By Ilia Yordanov, ; C++ Resources

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Computer Science 330 Assignment

Sample Paper 2013 SUB: COMPUTER SCIENCE GRADE XII TIME: 3 Hrs Marks: 70

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

Chapter 3: Input/Output

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

Fig: iostream class hierarchy

Streams - Object input and output in C++

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

And Even More and More C++ Fundamentals of Computer Science

Lecture 3 The character, string data Types Files

File Processing in C++

CS201 Latest Solved MCQs

C++ Input/Output: Streams

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

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

SPLIT-UP SYLLABUS ----CHENNAI REGION COMPUTER SCIENCE (Code: 083) Class-XII Academic Session

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


by Pearson Education, Inc. All Rights Reserved. 2

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

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

Object Oriented Pragramming (22316)

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

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

Files. In this lesson you will learn how to create and read files. There are two types of files that we will look at: text files and binary files.

C++ Input/Output Chapter 4 Topics

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Transcription:

File handling in C++ In most of the real time programming problems we need to store the data permanently on some secondary storage device so that it can be used later. Whenever we have to store the data permanently we use files. A file is used to store the data permanently. In C++ a stream is a general name given to a sequence of bytes. Each stream is associated with a particular class, which contains the member functions and definitions for dealing with that particular kind of data flow. In C++ whenever a file has to be used it should first be associated with an object of an appropriate stream class(ifstream, ofstream, or fstream). These classes actually have the following class hierarchy: ios istream ostream iostream ifstream ofstream fstream The ifstream, ofstream, and fstream classes are declared in the 'fstream.h' header file. This file also includes the 'iostream.h' header file. Therefore there is no need to include 'iostrream.h' in a program in which 'fstream.h' is also included. Different operations which can be performed on files are: 1. Writing/Appending data to a file 2. Reading data from a file 3. Deleting data from a file 4. Modifying some existing data in a file File opening modes: Whatever operation we want to perform on a file, the file has to be opened in appropriate mode(s) discussed below: 1. Input Mode: If a file is opened in input mode, data can only be input (i.e. read) from the file. Specified by - ios::in 2. Output Mode: If a file is opened in output mode, data can only be output (i.e. written) to the file. When a file is opened in output mode, the computer creates it on the secondary storage device and if the file already exists, computer overwrites it. (erasing the contents of the existing file). Specified by ios::out (YK: 9971709998) 1/9

3. InputOutput Mode: If a file is opened in I/O mode, then data can be input (i.e. read) from the file, as well as data can be output (written) to the file. When a file is opened in I/O mode then computer open the file, if it already exists on the secondary storage device and sets the file pointer to the beginning of the file (byte number 0). If the file es not exist, then computer creates it. Specified by ios::in ios::out 4. Append Mode: If a file is opened in Append mode then data can only be appended to the file, i.e. data can be added at the end of an already existing file. If the file es not already exist, then the file is created and data can be written into the file. Specified by ios::app 5. Truncate Mode: If a file is opened in Truncate mode then data is appended to the file by default. If the file es not already exist, then the file is created. Here one additional facility is that data can be written any where in the file by manipulating the put pointer. Specified by ios::ate In C++, whenever a file is defined as an object of ifstream, it is opened in input mode by default. ifstream class provides an input stream to input from a file using a file buffer. This class is derived from fstreambase and istream classes. Member functions of ifstream class are: open(), get(), getline(), read(), seekg(), tellg(), and close(). ofstream class provides an output stream to extract data from a file using a file buffer. Therefore whenever a file is defined to be an object of ofstream class, it is opened in output mode by default. This class is derived from fstreambase and ostream which are in turn derived from ios. Member functions of ofstream class are: open(), put(), write(), seekp(), tellp(), and close() fstream class is derived from ifstream and ofstream classes. Therefore if a file is defined to be an object of fstream class it can be opened in any mode. Opening a file: In C++ a file can be opened in two ways: 1) Using open() function, and 2)Using contsructor method. Reading from a file: Reading from a file can be ne in different ways when no. of records to be read is not known: a. while (df.read((char*)&s, sizeof(s))) b. df.read((char*)&s,sizeof(s)); while(df) df.read((char*)&s,sizeof(s)); c. df.read((char*)&s,sizeof(s)); while(!df.eof()) df.read((char*)&s,sizeof(s)); (YK: 9971709998) 2/9

Accessing the records Directly: seekg(): seekg() function is used to adjust the value of get pointer of a file. It can be used in two ways. First, where the single argument represents the position. Second, with two arguments where first represents an offset from a particular location in the file, and the second specifies the location from which the offset is measured. it can be beg, cur, or end, meaning beginning, current position and end of file respectively. e.g. the statement seekg(-10,ios::end) will set the get pointer to 10 bytes before the end of the file. tellg(): tellg() function returns the current value of the get pointer of a file. //To count the total number of records in the file student s; int n; ifstream df("student.dat"); df.seekg(0,ios::end); n = df.tellg()/sizeof(s); cout<<"file contains "<<n<<" record\n"; df.close(); //To display the 2 nd last and then the 3 rd last record student s; ifstream df; df.open("student.dat"); df.seekg(-2*sizeof(s),ios::end) df.read((char*)&s, sizeof(s)); df.seekg(-2*sizeof(s),ios::cur); df.read((char*)&s, sizeof(s)); df.close(); seekp() and tellp() work exactly as seekg() and tellg() respectively. A complete program: #include <fstream.h> #include <conio.h> #include <stdio.h> class student private: char name[20]; int roll_no; float marks; public: void getdata() cout<<"\nenter NAME:"; cin>>name; (YK: 9971709998) 3/9

s; cout<<"\nenter ROLL NO:"; cin>>roll_no; cout<<"enter MARKS:"; cin>>marks; void showdata() cout<<"\nname : "<<name; cout<<"\nroll NO: "<<roll_no; cout<<"\nmarks : "<<marks; int give_roll() return roll_no; int count_rec(char *fn) int count = 0; fstream file(fn,ios::in); while(file.read((char*)&s, sizeof(s))) count++; //(alternative/more efficient method) file.seekg(0,ios::end); int pos = file.tellg(); count = pos/sizeof(s); return count; void append(char* fn) student s; char option; fstream file; file.open(fn,ios::app); s.getdata(); file.write((char*)&s,sizeof(s)); cout<<"\nmore data (y/n)? "; cin>>option; while (option == 'y'); void delet(char *fn) int n, count; fstream file; count = count_rec(fn); cout<<"\nenter the record no. to delete:"; (YK: 9971709998) 4/9

cin>>n; if (n < 1 n > count) cout<<"\ninvalid record number, please reenter: "; while (n < 1 n > count); ofstream df1("temp.dat"); while(file.read((char*)&s,sizeof(s))) if(s.give_roll()!=r) df1.write((char*)&s,sizeof(s)); df1.close(); remove(fn); rename( temp.dat,fn); void Modify(char *fn) //to modify a particular record int n, count = count_rec(fn); fstream file; cout<<"\nenter the record no. to modify:"; cin>>n; if (n < 1 n > count) cout<<"\ninvalid record number, please reenter: "; while (n < 1 n > count); file.open(fn,ios::in ios::out); int pos = (n-1)*sizeof(s); file.seekg(pos); file.read((char*)&s, sizeof(s)); cout<<"\npresent contents of record number "<<n<<": "; cout<<"\nenter new data for record number "<<n<<": "; s.getdata(); if (file.eof()) file.open(fn,ios::in ios::out); file.seekg(pos); file.write((char*)&s, sizeof(s)); void Modify_R(char *fn) //to modify a particular record for a given roll no. int n; fstream file; int R; int found = 0; (YK: 9971709998) 5/9

int pos; cout<<"\nenter the roll no. to modify:"; cin>>r; file.open(fn,ios::in ios::out); while (file.read((char*)&s, sizeof(s))) if (s.give_roll() == R) found = 1; pos = file.tellg()-sizeof(s); if (found == 1) file.seekg(pos); file.read((char*)&s, sizeof(s)); cout<<"\npresent contents of roll number "<<R<<": "; cout<<"\nenter new data: "; s.getdata(); file.seekp(pos); file.write((char*)&s, sizeof(s)); else cout<<"\nrecord not found"; void Display(char *fn, int n) //to display nth record fstream file; int count = count_rec(fn); cout<<"\nwhich record number you want to see (1 - " <<count<<")? "; cin>>n; if (n < 1 n > count) cout<<"\ninvalid record number, please reenter: "; while (n < 1 n > count); for (int i = 1; i < n; i++) (file.read((char*)&s, sizeof(s))); file.read((char*)&s, sizeof(s)); //alternative method to display nth record int pos = (n-1)*sizeof(s); file.seekg(pos); file.read((char*)&s, sizeof(s)); (YK: 9971709998) 6/9

void Display(char *fn) //To display all the records present in the file. cout<<"\nthe file contains the following records: \n"; fstream file; while(file.read((char*)&s, sizeof(s))) void main() clrscr(); fstream file; char *fn = "student.dat"; int option; clrscr(); cout<<"\n1. Append" <<"\n2. Delete" <<"\n3. Modify - Rec. No." <<"\n4. Modify - Roll No." <<"\n5. Display" <<"\n6. Exit" <<"\n\nenter your choice: "; cin>>option; switch(option) case 1: append(fn); case 2: delet(fn); case 3: Modify(fn); case 4: Modify_R(fn); case 5: Display(fn); getch(); while (option!= 6); Other opening modes in C++: ios::ate ios::app This moves the file pointer to end of the file. I/O operations can still occur anywhere within the file, get and put pointer both can be manipulated. This opens the file so that whatever you write in the file is appended to the end, (YK: 9971709998) 7/9

ios::nocreate ios::noreplace ios::binary only get pointer can be manipulated. This causes the open() function to fail if the specified file es not already exist. It will not create a new file with the same name. This causes the open() function to fail if the specified file already exists, unless ate or app is set. By default a file is opened in text mode. By this mode it is specified that the file will be a binary file i.e. no character translation takes place. Types of data files: Data files can be divided into two types: (i)text File, and (ii) Binary file. Till now whatever files we have handled in this chapter were binary files. There are some differences between text files and binary files. TEXT FILE In a text file data is stored in the form of lines of text. A text file can be created as well as accessed using a C++ program or any text editor or using COPY command in DOS. A text file can easily be displayed using TYPE command in DOS. A textfile is readable as well as printable. BINARY FILE In a binary file data is stored in the form of sequence of bytes. There is no concept of lines in a Binary file. A Binary file can be created as well as accessed using a program only. A binary file cannot be displayed meaningfully using TYPE command in DOS. A binary file is neither readable nor printable. Member functions for text files: get(): get(char ch) : get(char a[n], n, 'delimiter') getline(): getline(char a[n],n) : getline(char a[n],n,'delimiter') put(): put(char ch) Member functions for binary files: read(), write() For both text and binary files: Extraction operator(>>) It reads the data(irrespective of the data type) from the associated stream till a white space or "\n" or the data type terminates which ever is encountered first in the input stream. Insertion operator(<<) It writes the data (irrespective of the data type) to the associated stream from the variable. close() It disconnects the link between the file object and the data file. Open() It sets up the link between the file object and the data file. (YK: 9971709998) 8/9

Exercises 1. A data file contains only integer values. Which of the following functions: (i) read, (ii) get() will you use to read data from the file? Justify your answer. 2. What is a stream? Name the streams generally used for file I/O. 3. What is the base class for most of the stream classes? 4. Write a statement that will create an object called salefile of the ofstream class and associate it with a file named "Sales.98". 5. Write an if statement that checks if an ifstream object called "infile" has reached end of file or has encountered an error. 6. Write a statement that writes a single character to an object called fileout which is of the class Ofstream. 7. Write a statement that will read the contents of an ifstream object called ifile into an array called buff. 8. Write a statement that moves the current position 13 bytes backward in a stream object called f1. 9. Distinguish between write() and put() functions of ostream class. 10. Differentiate between get() and read() functions of istream class. 11. What are the two methods of opening files? How are these different? 12. How are binary files different from text files in C++? 13. Declare a structure in C++ telerec, containing name (20 characters) and telephone number. A binary data file "TELE.DAT" stores data of the type telerec. Write functions in C++ to the following: a. to append records in the file. b. display the name for a given telephone number. If the telephone number es not exist then display error message "record not found". 14. A data file TELE.DAT contains names and telephone numbers as two of its fields. Write an interactive menu driven C++ program to the following: a. Search for telephone number(s) for a given name. b. Determine the name if the telephone number is known. 15. A binary file "EMPLOYEE.DAT" contains EMPNO (employee number), WRATE (hourly wage rate), NOH (number of hours worked/week) fields. Write a C++ function to read each record, compute weekly wages as WRATE*NOH and display EMPNO, WRATE, NOH, WRATE*NOH. 16. Write a C++ program that reads a text file and creates another file that is identical to it except that every sequence of consecutive blank spaces is replaced by a single blank space. 17. Write an interactive C++ program to create, append and display a text file. In case number of lines exceeds 22, file should be displayed one screen at a time. 18. Write an interactive C++ program to open a text file and then display the following: a. Frequency table of all the alphabetic characters. b. Number of numeric characters present in the file. 19. A data file contains the name of students and their marks in the following format: Ajay 350 Vijay 340 where name and marks are separated by either a space or a tab and end of line is a record separator. Write a program to read the file and display the records in two columns name and marks. Within the name column, the students' names are to be left justified and marks are to be right justified in the marks column. 20. There are two payroll files COMP1.DAT and COMP2.DAT. Each of the files has following fields: EmpNo: Integer, Name : A string of 20 characters, Payroll : A floating point number. Both the files are sorted in the increasing order of the EmpNo. Write a program to merge the two files and obtain a third file NEWCOMP.DAT. Do not use arrays for merging and sorting of the files. You can assume that the EmpNo are unique. (YK: 9971709998) 9/9