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

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

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

Chapte t r r 9

Chapter-12 DATA FILE HANDLING

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

C++ Programming Lecture 10 File Processing

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

Unit-V File operations

Object Oriented Programming In C++

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

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

C++ files and streams. Lec 28-31

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

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

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

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

Page 1

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

Module 11 The C++ I/O System

IS 0020 Program Design and Software Tools

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

Writing a Good Program. 7. Stream I/O

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

Input and Output File (Files and Stream )

Downloaded from

ios ifstream fstream

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

BITG 1113: Files and Stream LECTURE 10

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

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

Streams - Object input and output in C++

We can even use the operator << to chain the output request as:

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

Study Material for Class XII. Data File Handling

Random File Access. 1. Random File Access

UNIT V FILE HANDLING

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

Lecture 9. Introduction

Objects and streams and files CS427: Elements of Software Engineering

File handling Basics. Lecture 7

Chapter 12: Advanced File Operations

Advanced I/O Concepts

Streams contd. Text: Chapter12, Big C++

Fall 2017 CISC/CMPE320 9/27/2017

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

10/23/02 21:20:33 IO_Examples

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

Chapter 14 Sequential Access Files

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

More File IO. CIS 15 : Spring 2007

COMP322 - Introduction to C++

Fundamentals of Programming Session 27

Chapter 3 - Notes Input/Output

C++ Input/Output: Streams

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

EP241 Computing Programming

Object Oriented Programming

DISK FILE PROGRAM. ios. ofstream

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

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

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

by Pearson Education, Inc. All Rights Reserved. 2

Object Oriented Programming CS250

Generate error the C++ way

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

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Lecture 3 The character, string data Types Files

Chapter 8 File Processing

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

Come and join us at WebLyceum

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

Lecture 5 Files and Streams

COMP322 - Introduction to C++

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

Fig: iostream class hierarchy

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


Introduction. Lecture 5 Files and Streams FILE * FILE *

Input/Output Streams: Customizing

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

Fundamental File Processing Operations 2. Fundamental File Processing Operations

System Design and Programming II

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

CS201 Solved MCQs.

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

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

C++ How to Program 14.6

UNIT- 3 Introduction to C++

C++ Input/Output Chapter 4 Topics

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

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

Simple File I/O.

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

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

Chapter 21 - C++ Stream Input/Output

by Pearson Education, Inc. All Rights Reserved. 2

CS201 Latest Solved MCQs

Applications with Files, Templates

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Transcription:

File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place. Binary file - It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here. Classes for file stream operation ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files. Opening a file OPENING FILE USING CONSTRUCTOR ofstream outfile("sample.txt"); //output only ifstream infile( sample.txt ); //input only OPENING FILE USING open() Stream-object.open( filename, mode) ofstream outfile; outfile.open("sample.txt"); ifstream infile; infile.open("sample.txt"); File mode parameter Meaning ios::app Append to end of file ios::ate go to end of file on opening EduOnCloud.com Page 1

ios::binary file open in binary mode ios::in open file for reading only ios::out open file for writing only ios::nocreate open fails if the file does not exist ios::noreplace open fails if the file already exist ios::trunc delete the contents of the file if it exist All these flags can be combined using the bitwise operator OR ( ). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open(): fstream file; file.open ("example.bin", ios::out ios::app ios::binary); Closing File outfile.close(); infile.close(); INPUT AND OUTPUT OPERATION put() and get() function the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream. example : file.get(ch); file.put(ch); write() and read() function write() and read() functions write and read blocks of binary data. example: EduOnCloud.com Page 2

file.read((char *)&obj, sizeof(obj)); file.write((char *)&obj, sizeof(obj)); ERROR HANDLING FUNCTION FUNCTION RETURN VALUE AND MEANING eof() returns true (non zero) if end of file is encountered while reading; otherwise return false(zero) fail() return true when an input or output operation has failed bad() returns true if an invalid operation is attempted or any unrecoverable error has occurred. good() returns true if no error has occurred. File Pointers And Their Manipulation All i/o streams objects have, at least, one internal stream pointer: ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation. ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written. Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself derived from both istream and ostream). These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions: seekg() moves get pointer(input) to a specified location seekp() moves put pointer (output) to a specified location EduOnCloud.com Page 3

tellg() gives the current position of the get pointer tellp() gives the current position of the put pointer The other prototype for these functions is: seekg(offset, refposition ); seekp(offset, refposition ); The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class. ios::beg start of the file ios::cur current position of the pointer ios::end end of the file example: file.seekg(-10, ios::cur); Basic Operation On Text File In C++ File I/O is a five-step process: 1. Include the header file fstream in the program. 2. Declare file stream object. 3. Open the file with the file stream object. 4. Use the file stream object with >>, <<, or other input/output functions. 5. Close the files. Following program shows how the steps might appear in program. Program to write in a text file #include <fstream> using namespace std; int main() ofstream fout; fout.open("out.txt"); EduOnCloud.com Page 4

char str[300] = "Time is a great teacher but unfortunately it kills all its pupils. Berlioz"; //Write string to the file. fout << str; fout.close(); return 0; Program to read from text file and display it #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); char ch; while(!fin.eof()) fin.get(ch); cout << ch; fin.close(); return 0; Program to count number of characters. #include<fstream> #include<iostream> using namespace std; EduOnCloud.com Page 5

int main() ifstream fin; fin.open("out.txt"); int count = 0; char ch; while(!fin.eof()) fin.get(ch); count++; cout << "Number of characters in file are " << count; fin.close(); return 0; Program to count number of words #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); int count = 0; char word[30]; while(!fin.eof()) fin >> word; count++; EduOnCloud.com Page 6

cout << "Number of words in file are " << count; fin.close(); return 0; Program to count number of lines #include<fstream> #include<iostream> using namespace std; int main() ifstream fin; fin.open("out.txt"); int count = 0; char str[80]; while(!fin.eof()) fin.getline(str,80); count++; cout << "Number of lines in file are " << count; fin.close(); return 0; Program to copy contents of file to another file. #include<fstream> using namespace std; int main() EduOnCloud.com Page 7

ifstream fin; fin.open("out.txt"); ofstream fout; fout.open("sample.txt"); char ch; while(!fin.eof()) fin.get(ch); fout << ch; fin.close(); fout.close(); return 0; Basic Operation On Binary File In C++ When data is stored in a file in the binary format, reading and writing data is faster because no time is lost in converting the data from one format to another format. Such files are called binary files. This following program explains how to create binary files and also how to read, write, search, delete and modify data from binary files. #include<iostream> #include<fstream> #include<cstdio> using namespace std; class Student int admno; char name[50]; public: void setdata() cout << "\nenter admission no. "; cin >> admno; EduOnCloud.com Page 8

cout << "Enter name of student "; cin.getline(name,50); void showdata() cout << "\nadmission no. : " << admno; cout << "\nstudent Name : " << name; int retadmno() return admno; ; /* * function to write in a binary file. */ void write_record() ofstream outfile; outfile.open("student.dat", ios::binary ios::app); Student obj; obj.setdata(); outfile.write((char*)&obj, sizeof(obj)); outfile.close(); /* * function to display records of file */ void display() EduOnCloud.com Page 9

ifstream infile; infile.open("student.dat", ios::binary); Student obj; while(infile.read((char*)&obj, sizeof(obj))) obj.showdata(); infile.close(); /* * function to search and display from binary file */ void search(int n) ifstream infile; infile.open("student.dat", ios::binary); Student obj; while(infile.read((char*)&obj, sizeof(obj))) if(obj.retadmno() == n) obj.showdata(); infile.close(); /* * function to delete a record */ void delete_record(int n) EduOnCloud.com Page 10

Student obj; ifstream infile; infile.open("student.dat", ios::binary); ofstream outfile; outfile.open("temp.dat", ios::out ios::binary); while(infile.read((char*)&obj, sizeof(obj))) if(obj.retadmno()!= n) outfile.write((char*)&obj, sizeof(obj)); infile.close(); outfile.close(); remove("student.dat"); rename("temp.dat", "student.dat"); /* * function to modify a record */ void modify_record(int n) fstream file; file.open("student.dat",ios::in ios::out); Student obj; while(file.read((char*)&obj, sizeof(obj))) if(obj.retadmno() == n) cout << "\nenter the new details of student"; obj.setdata(); EduOnCloud.com Page 11

int pos = -1 * sizeof(obj); file.seekp(pos, ios::cur); file.write((char*)&obj, sizeof(obj)); file.close(); int main() //Store 4 records in file for(int i = 1; i <= 4; i++) write_record(); //Display all records cout << "\nlist of records"; display(); //Search record cout << "\nsearch result"; search(100); //Delete record delete_record(100); cout << "\nrecord Deleted"; //Modify record cout << "\nmodify Record 101 "; modify_record(101); return 0; Overloading I/O operator EduOnCloud.com Page 12

Overloaded to perform input/output for user defined datatypes. Left Operand will be of types ostream& and istream& Function overloading this operator must be a Non-Member function because left operand is not an Object of the class. It must be a friend function to access private data members. You have seen above that << operator is overloaded with ostream class object cout to print primitive type value output to the screen. Similarly you can overload << operator in your class to print user-defined type to screen. For example we will overload << in time class to display time object using cout. time t1(3,15,48); cout << t1; NOTE: When the operator does not modify its operands, the best way to overload the operator is via friend function. Example: overloading '<<' Operator to print time object #include< iostream.h> #include< conio.h> class time int hr,min,sec; public: time() hr=0, min=0; sec=0; time(int h,int m, int s) EduOnCloud.com Page 13

hr=h, min=m; sec=s; friend ostream& operator << (ostream &out, time &tm); //overloading '<<' ope rator ; ostream& operator<< (ostream &out, time &tm) //operator function out << "Time is " << tm.hr << "hour : " << tm.min << "min : " << tm.sec << " sec"; return out; void main() time tm(3,15,45); cout << tm; Output Time is 3 hour : 15 min : 45 sec Manipulators : Stream manipulators Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example: cout << boolalpha; EduOnCloud.com Page 14

They are still regular functions and can also be called as any other function using a stream object as argument, for example: boolalpha (cout); Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters. C++ provides many predefined manipulators but you can also create yourown manipulators. The syntax for creating user defined manipulators is defined as follows: ostream&manipulator_name(ostream&ostrobj) set of statements; return ostrobj; Example: #include < iostream.h> #include < iomanip.h> ostream&curr(ostream&ostrobj) cout << fixed << setprecision(2); cout << "Rs."; returnostrobj; void main() floatamt = 10.5478; EduOnCloud.com Page 15

cout << curr << amt; Manipulators are special stream functions that are used to change certain characteristics of the input and output. Include < iomanip.h> header file for using these manipulators in your c++ program. The following are the list of important manipulator used in a C++. - Endl - hex, dec, oct - setbase - setw - setfill - setprecision - ends - ws - flush - setiosflags - resetiosflags endl : The endl is an output manipulator that is used to generate a carriage return. It works like \n Setbase() : The setbase() manipulator is used to convert the base of one numeric value into another base. Setw () : It is used to specify the minimum number of character positions, a variable will consume on the command prompt. The general syntax of the setw manipulator function is setw(int width ) Setfill() It is used to specify a different character to fill the unused space. The general syntax of the setfill ( ) manipulator is setfill( char c) EduOnCloud.com Page 16

Example: setfill ( * ) / / fill an asterisk (*) character setprecision(): Itis used with floating point numbers. You can set the number of digits printed to the right of the decimal point. #include< iostream.h> #include< iomanip.h> void main (void) int value; float a,b,c; a = 350; b = 200; c = a/b; cout << " Enter number" << endl; cin >> value; cout << " Hexadecimal base =" << hex << value << endl; cout << " Octal base =" << oct << value << endl; cout << " hexadecimal base = " << setbase (16); cout << value << endl; cout << " Octal base = " << setbase (8) << value << endl; cout << setfill ('*'); cout << setw (5) << a << setw (5) << b << endl; cout << setw (6) << a << setw (6) << b << endl; cout << setw (7) << a << setw (7) << b << endl; cout << fixed << setprecision (2) << c << endl; EduOnCloud.com Page 17

Output: Enter number 100 Hexadecimal base =64 Octal base =144 hexadecimal base = 64 Octal base = 144 **350**200 ***350***200 ****350****200 1.75 EduOnCloud.com Page 18