Unit-V File operations

Similar documents
Object Oriented Programming In C++

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

Chapte t r r 9

ios ifstream fstream

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

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

Developed By : Ms. K. M. Sanghavi

C++ files and streams. Lec 28-31

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

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

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

C++ Programming Lecture 10 File Processing

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

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

Study Material for Class XII. Data File Handling

Chapter 14 Sequential Access Files

by Pearson Education, Inc. All Rights Reserved. 2

Fall 2017 CISC/CMPE320 9/27/2017

Random File Access. 1. Random File Access

Writing a Good Program. 7. Stream I/O

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

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

Advanced I/O Concepts

Lecture 9. Introduction

DISK FILE PROGRAM. ios. ofstream

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

Streams contd. Text: Chapter12, Big C++

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

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

Page 1

Understanding main() function Input/Output Streams

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

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

Chapter 12: Advanced File Operations

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

Fundamentals of Programming Session 27

Lecture 5 Files and Streams

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

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

Input and Output File (Files and Stream )

Chapter 8 File Processing

UNIT V FILE HANDLING

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

File handling Basics. Lecture 7

Module 11 The C++ I/O System

Applications with Files, Templates

Object Oriented Programming

Downloaded from

Introduction. Lecture 5 Files and Streams FILE * FILE *

Module C++ I/O System Basics

Object Oriented Programming CS250

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

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

BITG 1113: Files and Stream LECTURE 10

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

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

CS201 Latest Solved MCQs

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

Fundamental File Processing Operations 2. Fundamental File Processing Operations

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

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

by Pearson Education, Inc. All Rights Reserved. 2

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

by Pearson Education, Inc. All Rights Reserved. 2

Streams - Object input and output in C++

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

Simple File I/O.

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

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

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

System Design and Programming II

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

C++ How to Program 14.6

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

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

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

Stream States. Formatted I/O

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

Object Oriented Programming

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

COMP322 - Introduction to C++

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

Fig: iostream class hierarchy

Object Oriented Programming

JB Academy, Faizabad Half Yearly Examination Subject: Computer Science (083) Class XII

File Processing in C++

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

Developed By : Ms. K. M. Sanghavi

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

Chapter 3 - Notes Input/Output

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

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

More File IO. CIS 15 : Spring 2007

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

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

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

Transcription:

Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the data written to cout or read from cin. C++ provides standard iostream library to operate with streams. The iostream is an object-oriented library which provides Input/Output functionality using streams. In the above figure, ios is the base class. The iostream class is derived from istream and ostream classes. The ifstream and ofstream are derived from istream and ostream, respectively. These classes handle input and output with the disk files. The fstream.h header file contains a declaration of ifstream, ofstream and fstream classes. The iostream.h file contains istream, ostream and iostream classes and included in the program while doing disk I/O operations. The filebuf class contains input and output operations with files. The streambuf class does not organize streams for input and output operations, only derived classes of streambuf performs I/O operations. These derived classes arrange a space for keeping input data and for sending output data. C++ stream classes In input operations, data bytes flow from an input source (such as keyboard, file, network or another program) into the program. In output operations, data bytes flow

from the program to an output sink (such as console, file, network or another program). Streams acts as an intermediaries between the programs and the actual IO devices, in such the way that frees the programmers from handling the actual devices, so as to archive device independent IO operations. C++ provides both the formatted and unformatted IO functions. In formatted or highlevel IO, bytes are grouped and converted to types such as int, double, string or userdefined types. In unformatted or low-level IO, bytes are treated as raw bytes and unconverted. Formatted IO operations are supported via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a consistent public IO interface. The istream and ostream invokes the filebuf functions to perform the insertion or extraction on the streams. I/O Stream Meaning istream ostream ifstream Input File Stream Input Stream It reads and interprets input. Description Output stream It can write sequences of characters and represents other kinds of data. The ifstream class is derived from fstreambase and istream by multiple inheritance. This class accesses the member functions such as get(), getline(), seekg(), tellg() and read(). It provides open() function with the default input mode and allows input operations. ofstream Output File Stream The ofstream class is derived from fstreambase and ostream classes. This class accesses the member functions such as put(), seekp(), write() and tellp().

It provides the member function open() with the default output mode. fstream File Stream The fstream allows input and output operations simultaneous on a filebuf. It invokes the member function istream::getline() to read characters from the file. This class provides the open() function with the default input mode. fstreambase File Stream Base It acts as a base class for fstream, ifstream and ofstream. The open() and close() functions are defined in fstreambase. Advantages of Stream Classes Stream classes have good error handling capabilities. These classes work as an abstraction for the user that means the internal operation is encapsulated from the user. These classes are buffered and do not uses the memory disk space. These classes have various functions that make reading or writing a sequence of bytes easy for the programmer. Classes for file stream operations In Files we store data i.e. text or binary data permanently and use these data to read or write in the form of input output operations by transferring bytes of data. So we use the term File Streams/File handling. We use the header file <fstream.h> ofstream: It represents output Stream and this is used for writing in files. ifstream: It represents input Stream and this is used for reading from files. fstream: It represents both output Stream and input Stream. So it can read from files and write to files. Input/Output Streams The iostream standard library provides cin and cout object.

Input stream uses cin object for reading the data from standard input and Output stream uses cout object for displaying the data on the screen or writing to standard output. The cin and cout are pre-defined streams for input and output data. Syntax: cin>>variable_name; cout<<variable_name; The cin object uses extraction operator (>>) before a variable name while the cout object uses insertion operator (<<) before a variable name. The cin object is used to read the data through the input device like keyboard etc. while the cout object is used to perform console write operation. Operations in File Handling: Creating a file: open() Reading data: read() Writing new data: write() Closing a file: close() Creating/Opening a File We create/open a file by specifying new path of the file and mode of operation. Operations can be reading, writing, appending and truncating. Syntax for file creation: FilePointer.open("Path",ios::mode); Example of file opened for writing: st.open("e:\study.txt",ios::out); Example of file opened for reading: st.open("e:\study.txt",ios::in); Example of file opened for appending: st.open("e:\study.txt",ios::app); Example of file opened for truncating: st.open("e:\study.txt",ios::trunc); #include<iostream.h> #include<conio.h> #include <fstream.h> using namespace std;

int main() fstream st; // Step 1: Creating object of fstream class st.open("e:\study.txt",ios::out); // Step 2: Creating new file if(!st) // Step 3: Checking whether file exist cout<<"file creation failed"; else cout<<"new file created"; st.close(); // Step 4: Closing file getch(); return 0; Writing to a File #include <iostream.h> #include<conio.h> #include <fstream.h> using namespace std; int main() fstream st; // Step 1: Creating object of fstream class st.open("e:\study.txt",ios::out); // Step 2: Creating new file if(!st) // Step 3: Checking whether file exist cout<<"file creation failed";

else cout<<"new file created"; st<<"hello"; // Step 4: Writing to file st.close(); // Step 5: Closing file getch(); return 0; Here we are sending output to a file. So, we use ios::out. As given in the program, information typed inside the quotes after "FilePointer <<" will be passed to output file. Reading from a File #include <iostream.h> #include<conio.h> #include <fstream.h> using namespace std; int main() fstream st; // step 1: Creating object of fstream class st.open("e:\study.txt",ios::in); // Step 2: Creating new file if(!st) // Step 3: Checking whether file exist cout<<"no such file"; else char ch; while (!st.eof()) st >>ch; // Step 4: Reading from file

cout << ch; // Message Read from file st.close(); // Step 5: Closing file getch(); return 0; Here we are reading input from a file. So, we use ios::in. As given in the program, information from the output file is obtained with the help of following syntax "FilePointer >>variable". Close a File It is done by FilePointer.close(). #include <iostream.h> #include<conio.h> #include <fstream.h> using namespace std; int main() fstream st; // Step 1: Creating object of fstream class st.open("e:\study.txt",ios::out); // Step 2: Creating new file st.close(); // Step 4: Closing file getch(); return 0; File Modes - Reading and Writing Files In order to open a file with a stream object open() member function is used. open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same

type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags: Mode ios::ate ios::app ios::in ios::out ios::trunc Description Write all output to the end of file (even if file position pointer is moved with seekp) Open a file for output and move to the end of the existing data (normally used to append data to a file, but data can be written anywhere in the file The original file (if it exists) will not be truncated Open a file for output (default for ofstream objects) Discard the file's contents if it exists (this is also the default action for ios::out, if ios::ate, ios::app, or ios::in are not specified) Opens the file in binary mode (the default is text mode) ios::binary ios::nocreate Open fails if the file does not exist ios::noreplace Open files if the file already exists. Detection of end of file C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data to be read from an input file stream, and zero (meaning FALSE) otherwise. Rules for using end-of-file (eof( )): 1. Always test for the end-of-file condition before processing data read from an input file stream. a. use a priming input statement before starting the loop b. repeat the input statement at the bottom of the loop body 2. Use a while loop for getting data from an input file stream. A for loop is desirable only when you know the exact number of data items in the file, which we do not know. Special operations in a File There are few important functions to be used with file streams like: tellp() - It tells the current position of the put pointer. Syntax: filepointer.tellp() tellg() - It tells the current position of the get pointer.

Syntax: filepointer.tellg() seekp() - It moves the put pointer to mentioned location. Syntax: filepointer.seekp(no of bytes,reference mode) seekg() - It moves get pointer(input) to a specified location. Syntax: filepointer.seekg((no of bytes, reference point) put() - It writes a single character to file. get() - It reads a single character from file. Note: For seekp and seekg three reference points are passed: ios::beg - beginning of the file ios::cur - current position in the file ios::end - end of the file Below is a program to show importance of tellp, tellg, seekp and seekg: #include <iostream.h> #include<conio.h> #include <fstream.h> using namespace std; int main() fstream st; // Creating object of fstream class st.open("e:\study.txt",ios::out); // Creating new file if(!st) // Checking whether file exist cout<<"file creation failed"; else cout<<"new file created"<<endl; st<<"hello Friends"; //Writing to file

// Checking the file pointer position cout<<"file Pointer Position is "<<st.tellp()<<endl; st.seekp(-1, ios::cur); // Go one position back from current position //Checking the file pointer position cout<<"as per tellp File Pointer Position is "<<st.tellp()<<endl; st.close(); // closing file st.open("e:\study.txt",ios::in); // Opening file in read mode if(!st) //Checking whether file exist else cout<<"no such file"; char ch; st.seekg(5, ios::beg); // Go to position 5 from begning. cout<<"as per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file pointer position cout<<endl; st.seekg(1, ios::cur); //Go to position 1 from beginning. cout<<"as per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file pointer position st.close(); //Closing file getch(); return 0; New file created File Pointer Position is 13 As per tellp File Pointer Position is 12

As per tellg File Pointer Position is 5 As per tellg File Pointer Position is 6 C++ write() function The write() function is used to write object or record (sequence of bytes) to the file. A record may be an array, structure or class. Syntax of write() function fstream fout; fout.write( (char *) &obj, sizeof(obj) ); The write() function takes two arguments. &obj : Initial byte of an object stored in memory. sizeof(obj) : size of object represents the total number of bytes to be written from initial byte. Example of write() function #include<fstream.h> #include<conio.h> class Student int roll; char name[25]; float marks; void getdata() cout<<"\n\nenter Roll : "; cin>>roll; cout<<"\nenter Name : "; cin>>name; cout<<"\nenter Marks : ";

; cin>>marks; public: void AddRecord() fstream f; Student Stu; f.open("student.dat",ios::app ios::binary); Stu.getdata(); f.write( (char *) &Stu, sizeof(stu) ); f.close(); void main() Student S; char ch='n'; do S.AddRecord(); cout<<"\n\ndo you want to add another data (y/n) : "; ch = getche(); while(ch=='y' ch=='y'); cout<<"\ndata written successfully..."; Output : Enter Roll : 1 Enter Name : Ashish Enter Marks : 78.53

Do you want to add another data (y/n) : y Enter Roll : 2 Enter Name : Kaushal Enter Marks : 72.65 Do you want to add another data (y/n) : y Enter Roll : 3 Enter Name : Vishwas Enter Marks : 82.65 Do you want to add another data (y/n) : n Data written successfully... C++ read() function The read() function is used to read object (sequence of bytes) to the file. Syntax of read() function fstream fin; fin.read( (char *) &obj, sizeof(obj) ); The read() function takes two arguments. &obj : Initial byte of an object stored in file. sizeof(obj) : size of object represents the total number of bytes to be read from initial byte. The read() function returns NULL if no data read. Example of read() function #include<fstream.h> #include<conio.h>

class Student int roll; char name[25]; float marks; void putdata() cout<<"\n\t"<<roll<<"\t"<<name<<"\t"<<marks; public: void Display() fstream f; Student Stu; f.open("student.dat",ios::in ios::binary); cout<<"\n\troll\tname\tmarks\n"; while( (f.read((char*)&stu,sizeof(stu)))!= NULL ) Stu.putdata(); f.close(); ; void main() Student S; S.Display(); Output :

Roll Name Marks 1 Ashish 78.53 2 Kaushal 72.65 3 Vishwas 82.65