ios ifstream fstream

Size: px
Start display at page:

Download "ios ifstream fstream"

Transcription

1 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: ) 1/9

2 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: ) 2/9

3 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: ) 3/9

4 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: ) 4/9

5 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: ) 5/9

6 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: ) 6/9

7 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: ) 7/9

8 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: ) 8/9

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: ) 9/9

Unit-V File operations

Unit-V File operations 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

More information

Chapter-12 DATA FILE HANDLING

Chapter-12 DATA FILE HANDLING Chapter-12 DATA FILE HANDLING Introduction: A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform the read and write operations on these files.

More information

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

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.

More information

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

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 16 Files 16.1 Introduction At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file. 16.2 Objectives

More information

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Ch - 7. Data File Handling Introduction Data File Handling The fstream.h Header file Data Files Opening and Closing File Steps to process a File in your Program Changing the behavior of Stream Sequential I/O With Files Detecting

More information

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

Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on Computer programs are associated to work with files as it helps in storing data & information permanently. File - itself a bunch of bytes stored on some storage devices. In C++ this is achieved through

More information

Chapte t r r 9

Chapte t r r 9 Chapter 9 Session Objectives Stream Class Stream Class Hierarchy String I/O Character I/O Object I/O File Pointers and their manipulations Error handling in Files Command Line arguments OOPS WITH C++ Sahaj

More information

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing 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

More information

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

Object Oriented Programming Using C++ UNIT-3 I/O Streams 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.

More information

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

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes: C++ Binary File I/O C++ file input and output are typically achieved by using an object of one of the following classes: ifstream for reading input only. ofstream for writing output only. fstream for reading

More information

Study Material for Class XII. Data File Handling

Study Material for Class XII. Data File Handling Study Material for Class XII Page 1 of 5 Data File Handling Components of C++ to be used with handling: Header s: fstream.h Classes: ifstream, ofstream, fstream File modes: in, out, in out Uses of cascaded

More information

Object Oriented Programming In C++

Object Oriented Programming In C++ C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.

More information

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

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files. C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

C++ files and streams. Lec 28-31

C++ files and streams. Lec 28-31 C++ files and streams Lec 28-31 Introduction So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output

More information

Random File Access. 1. Random File Access

Random File Access. 1. Random File Access Random File Access 1. Random File Access In sequential file access, the file is read or written sequentially from the beginning. In random file access, you can skip around to various points in the file

More information

DISK FILE PROGRAM. ios. ofstream

DISK FILE PROGRAM. ios. ofstream [1] DEFINITION OF FILE A file is a bunch of bytes stored on some storage media like magnetic disk, optical disk or solid state media like pen-drive. In C++ a file, at its lowest level is interpreted simply

More information

Downloaded from

Downloaded from DATA FILE HANDLING IN C++ Key Points: Text file: A text file stores information in readable and printable form. Each line of text is terminated with an EOL (End of Line) character. Binary file: A binary

More information

Developed By : Ms. K. M. Sanghavi

Developed By : Ms. K. M. Sanghavi Developed By : Ms. K. M. Sanghavi Designing Our Own Manipulators We can design our own manipulators for certain special purpose.the general form for creating a manipulator without any arguments is: ostream

More information

Chapter 14 Sequential Access Files

Chapter 14 Sequential Access Files Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 In Fig. 17.4, the file is to be opened for output, so an ofstream object is created. Two arguments are passed to the object s constructor the filename and the file-open mode (line 12). For an ofstream

More information

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

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

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

C++ does not, as a part of the language, define how data are sent out and read into the program Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard

More information

Page 1

Page 1 Virtual Functions (introduction) A virtual function is one that does not really exist but it appears real in some parts of the program. Virtual functions are advanced features of the object oriented programming

More information

Advanced I/O Concepts

Advanced I/O Concepts Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations

More information

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

Streams in C++ Stream concept. Reference information. Stream type declarations Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read

More information

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

Consider the following example where a base class has been derived by other two classes: Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit IV Polymorphism The word polymorphism means having many forms. Typically, polymorphism occurs

More information

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

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING QUESTION BANK DEPARTMENT:EEE SEMESTER: V SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING UNIT III PART - A (2 Marks) 1. What are the advantages of using exception handling? (AUC MAY 2013) In C++,

More information

C++ How to Program 14.6

C++ How to Program 14.6 C++ How to Program 14.6 14.6 Random-Access Files pg.611-pg.612 -Unlike sequential files, R.A. files are instant-access applications. Any transaction-processing system. Requiring rapid access to specific

More information

File handling Basics. Lecture 7

File handling Basics. Lecture 7 File handling Basics Lecture 7 What is a File? A file is a collection of information, usually stored on a computer s disk. Information can be saved to files and then later reused. 2 File Names All files

More information

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

DATA FILE HANDLING FILES. characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s DATA FILE HANDLING The Language like C/C++ treat everything as a file, these languages treat keyboard, mouse, printer, Hard disk, Floppy disk and all other hardware as a file. In C++, a file, at its lowest

More information

High Order Thinking Skill Questions Subject : Computer Science Class: XII 1 Mark Questions Programming in C++ 1. Observe the program segment carefully and answer the question that follows: int getitem_no(

More information

Chapter 8 File Processing

Chapter 8 File Processing Chapter 8 File Processing Outline 1 Introduction 2 The Data Hierarchy 3 Files and Streams 4 Creating a Sequential Access File 5 Reading Data from a Sequential Access File 6 Updating Sequential Access Files

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

Input and Output File (Files and Stream )

Input and Output File (Files and Stream ) 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,

More information

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

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file. File Structures Physical Files and Logical Files Chap 2. Fundamental File Processing Operations Things you have to learn Physical files and logical files File processing operations: create, open, close,

More information

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

Advanced File Operations. Review of Files. Declaration Opening Using Closing. CS SJAllan Chapter 12 2 Chapter 12 Advanced File Operations Review of Files Declaration Opening Using Closing CS 1410 - SJAllan Chapter 12 2 1 Testing for Open Errors To see if the file is opened correctly, test as follows: in.open("cust.dat");

More information

Writing a Good Program. 7. Stream I/O

Writing a Good Program. 7. Stream I/O Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)

More information

Module 11 The C++ I/O System

Module 11 The C++ I/O System Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...

More information

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

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream Topics: Files and Stream In this lab session, you will learn very basic and most common I/O operations required for C++ programming. The second part of this tutorial will teach you how to read and write

More information

Input/Output Streams: Customizing

Input/Output Streams: Customizing DM560 Introduction to Programming in C++ Input/Output Streams: Customizing Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne Stroustrup]

More information

Object Oriented Programming CS250

Object Oriented Programming CS250 Object Oriented Programming CS250 Abas Computer Science Dept, Faculty of Computers & Informatics, Zagazig University arabas@zu.edu.eg http://www.arsaliem.faculty.zu.edu.eg Object Oriented Programming Principles

More information

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

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

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

SUBMITTED AS A PART OF C.B.S.E. CURRICULUM FOR THE YEAR SUBMITTED AS A PART OF C.B.S.E. CURRICULUM FOR THE YEAR 2008-09 CONTENTS CERTIFICATE ACKNOWLEDGEMENT PROJECT PREAMBLE PROJECT STUDY ALGORITHM SOURCE CODE OUTPUT CERTIFICATE This is to certify that, Roll

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Streams contd. Text: Chapter12, Big C++

Streams contd. Text: Chapter12, Big C++ Streams contd pm_jat@daiict.ac.in Text: Chapter12, Big C++ Streams Objects are Abstracted Wrapper around input/output source/destinations Steps in reading/writing streams- Open: Establish connection between

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

Chapter 12: Advanced File Operations

Chapter 12: Advanced File Operations Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed

More information

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

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

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

VuZs Team's Work. CS201 Spring Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May :52 CS201 Spring2009 5 Solved by vuzs Team with Reference Written by Administrator Wednesday, 19 May 2010 17:52 MIDTERM EXAMINATION Spring 2009 CS201- Introduction to Programming Shared & Solved by vuzs Team

More information

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

CS Programming2 1 st Semester H Sheet # 8 File Processing. Princess Nora University College of Computer and Information Sciences Princess Nora University College of Computer and Information Sciences CS 142-341 Programming2 1 st Semester 1434-1435 H Sheet # 8 File Processing Question#1 Write line of code to do the following: 1- Open

More information

Applications with Files, Templates

Applications with Files, Templates Files - Introduction A file is collection of data or information that has a name, called the filename. Files are stored in secondary storage devices such as floppy disks and hard disks. The main memories

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

BITG 1113: Files and Stream LECTURE 10

BITG 1113: Files and Stream LECTURE 10 BITG 1113: Files and Stream LECTURE 10 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of input & output files. 2. Use data files for input & output

More information

Introduction. Lecture 5 Files and Streams FILE * FILE *

Introduction. Lecture 5 Files and Streams FILE * FILE * Introduction Lecture Files and Streams C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file, and

More information

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

DE122/DC106 Object Oriented Programming with C++ DEC 2014 Q.2 a. Distinguish between Procedure-oriented programming and Object- Oriented Programming. Procedure-oriented Programming basically consists of writing a list of instructions for the computer to follow

More information

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

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file? CS162 External Data Files 1 External Files So far, all of our programs have used main memory to temporarily store

More information

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

(1)Given a binary file PHONE.DAT, containing records of the following structure type class Phonlist { char Name[20]; char Address[30]; char (1)Given a binary file PHONE.DAT, containing records of the following structure type class Phonlist char Name[20]; char Address[30]; char AreaCode[5]; char PhoneNo[15]; Public: void Register(); void Show();

More information

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

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program

More information

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

AC55/AT55 OBJECT ORIENTED PROGRAMMING WITH C++ DEC 2013 Q.2 a. Discuss the fundamental features of the object oriented programming. The fundamentals features of the OOPs are the following: (i) Encapsulation: It is a mechanism that associates the code and data

More information

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

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

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

Computer Science, Class XII, Chapter No.7 (Data File Handling) Chapter No.7 (Data File Handling) 1. What is a file? How a text file is different from binary file? 2. What is stream? Name and define the streams generally used for file I/O? 3. Which header file is required

More information

More File IO. CIS 15 : Spring 2007

More File IO. CIS 15 : Spring 2007 More File IO CIS 15 : Spring 2007 Functionalia Office Hours Today 2 to 3pm - 0317 N (Bridges Room) HW 2 due on Sunday March 11, 11:59pm Note: Midterm is on MONDAY, March 12th Review: Thursday Today: Survey

More information

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

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 Topic: File input/output I. Streams II. Access methods III. C++ style Input, output, random access Stream classes: ifstream, ofstream IV. C style The FILE data type Opening files Writing to, reading text

More information

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

SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) which generates a random number in the range of 0 to n-1. For example; SHORT REVIEW OF CS TOPICS RANDOM NUMBERS (2 MARKS) Generating Random Numbers The key function in generating random numbers is; int random (int n); which generates a random number in the range of 0 to n-1.

More information

UNIT V FILE HANDLING

UNIT V FILE HANDLING UNIT V CONTENTS: Streams and formatted I/O I/O manipulators File handling Random access Object serialization Namespaces Std namespace ANSI String Objects Standard template library FILE HANDLING Streams:

More information

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

All About: File I/O in C++ By Ilia Yordanov,  ; C++ Resources All About: File I/O in C++ By Ilia Yordanov, loobian@cpp-home.com www.cpp-home.com ; C++ Resources This tutorial may not be republished without a written permission from the author! Introduction This tutorial

More information

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

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard

More information

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Fundamental File Processing Operations 2. Fundamental File Processing Operations 2 Fundamental File Processing Operations Copyright 2004, Binnur Kurt Content Sample programs for file manipulation Physical files and logical files Opening and closing files Reading from files and writing

More information

Computer Science 330 Assignment

Computer Science 330 Assignment Computer Science 330 Assignment Note: All questions are compulsory. The marks for each question are given at the same place. Max. Marks: 20 (ii) Write your name, enrolment number, AI name and subject etc.

More information

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

Sample Paper 2013 SUB: COMPUTER SCIENCE GRADE XII TIME: 3 Hrs Marks: 70 Sample Paper 2013 SUB: COMPUTER SCIENCE GRADE XII TIME: 3 Hrs Marks: 70 INSTRUCTIONS: All the questions are compulsory. i. Presentation of answers should be neat and to the point. iii. Write down the serial

More information

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

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

Chapter 3: Input/Output

Chapter 3: Input/Output Chapter 3: Input/Output I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters

More information

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

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or

More information

Fig: iostream class hierarchy

Fig: iostream class hierarchy Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

More information

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

File I/O Christian Schumacher, Info1 D-MAVT 2013 File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential

More information

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

And Even More and More C++ Fundamentals of Computer Science And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Friendship Inheritance Multiple Inheritance Polymorphism Virtual Members Abstract Base Classes File Input/Output Friendship

More information

Lecture 3 The character, string data Types Files

Lecture 3 The character, string data Types Files Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',

More information

File Processing in C++

File Processing in C++ File Processing in C++ Data Representation in Memory Record: A subdivision of a file, containing data related to a single entity. Field : A subdivision of a record containing a single attribute of the

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() { Text File I/O We can use essentially the same techniques we ve been using to input from the keyboard and output to the screen and just apply them to files instead. If you want to prepare input data ahead,

More information

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

SPLIT-UP SYLLABUS ----CHENNAI REGION COMPUTER SCIENCE (Code: 083) Class-XII Academic Session SPLIT-UP SYLLABUS ----CHENNAI REGION COMPUTER SCIENCE (Code: 083) Class-XII Academic Session 2008-09 Sr.No. Duration Number of Working Days From To Topic to be Covered Nos. of Periods required CAL/TAL

More information

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

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

If the function modify( ) is supposed to change the mark of a student having student_no y in the file student.dat, write the missing statements to modify the student record. 10. Observe the program segment

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

More information

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

This can be thrown by dynamic_cast. This is useful device to handle unexpected exceptions in a C++ program Abstract class Exception handling - Standard libraries - Generic Programming - templates class template - function template STL containers iterators function adaptors allocators -Parameterizing the class

More information

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

Input/output. Remember std::ostream? std::istream std::ostream. std::ostream cin std::istream. namespace std { class ostream { /*... Input/output Remember std::ostream? namespace std { class ostream { /*... */ }; } extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; 7 / 24 std::istream std::ostream std

More information

Object Oriented Pragramming (22316)

Object Oriented Pragramming (22316) Chapter 1 Principles of Object Oriented Programming (14 Marks) Q1. Give Characteristics of object oriented programming? Or Give features of object oriented programming? Ans: 1. Emphasis (focus) is on data

More information

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

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

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

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,

More information

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.

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++: Files 1/1 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. Text files have variable length records.

More information

C++ Input/Output Chapter 4 Topics

C++ Input/Output Chapter 4 Topics Chapter 4 Topics Chapter 4 Program Input and the Software Design Process Input Statements to Read Values into a Program using >>, and functions get, ignore, getline Prompting for Interactive Input/Output

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information