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

Similar documents
File.seekp(File.tellp( )-sizeof(c)); //Statement 1 //File.seekp(Record*sizeof(C));

Downloaded from

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

Downloaded from

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

Data File Handling FILL IN THE BLANKS EACH QUESTION CARRY 1 MARK

Chapter-12 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

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

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

QUESTION BANK SUB: COMPUTER SCIENCE(083)

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

Unit-V File operations

Q4. Based on File Handling 6-8 Marks File Pointers tellg() tellp() seekp()seekg() 1-2 Marks Binary File 4 Marks Text file 2 Marks

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

Study Material for Class XII. Data File Handling

C++ Programming Lecture 10 File Processing

BRAIN INTERNATIONAL SCHOOL. Computer Science Assignment CLASS XII OCTOBER 2018 Chapter-7. Data File Handling in C++ Text Files

Chapte t r r 9

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

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

Chapter 12: Advanced File Operations

CHAPTER-7 Data File Handling

C++ files and streams. Lec 28-31

Developed By : Ms. K. M. Sanghavi

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

IS 0020 Program Design and Software Tools

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

Object Oriented Programming In C++

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

by Pearson Education, Inc. All Rights Reserved. 2

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

ios ifstream fstream

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

Input and Output File (Files and Stream )

Page 1

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


Random File Access. 1. Random File Access

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

Fundamentals of Programming Session 27

Writing a Good Program. 7. Stream I/O

Chapter 14 Sequential Access Files

Chapter 8 File Processing

Fundamental File Processing Operations 2. Fundamental File Processing Operations

Model Sample Paper 2015

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

Sample Paper, 2015 Subject: Computer Science Class 12 th

Streams contd. Text: Chapter12, Big C++

Advanced I/O Concepts

Lecture 9. Introduction

Fall 2017 CISC/CMPE320 9/27/2017

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

More File IO. CIS 15 : Spring 2007

Object Oriented Programming CS250

C++ How to Program 14.6

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

DISK FILE PROGRAM. ios. ofstream

91/1 COMPUTER SCIENCE. Series SHC/1. dksm ua- jksy ua- Code No. Roll No. Candidates must write the Code on the title page of the answer-book.

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

BITG 1113: Files and Stream LECTURE 10

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

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

CS201 Latest Solved MCQs

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

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

File handling Basics. Lecture 7

CLASS XII SECOND TERM EXAMINATION SUBJECT : COMPUTER SCIENCE SET A2 (SOLUTIONS)

DATA FILE HANDLING. The function should create another file OUT.TXT with the text

System Design and Programming II

UNIT V FILE HANDLING

Lecture 3 The character, string data Types Files

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

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

Applications with Files, Templates

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

Files Total: // Files Example 1. #include <iostream> #include <fstream>

KENDRIYA VIDYALAYA IIT CAMPUS CHENNAI 36 COMPUTER SCIENCE. Half Yearly

Guru Harkrishan Public School, Karol Bagh Pre Mock Class XII Sub: COMPUTER SCIENCE Allowed :3 hrs

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

DELHI PUBLIC SCHOOL BOKARO STEEL CITY

Stream States. Formatted I/O

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

COMPUTER SCIENCE (Theory) Class XII - Code : 083 Blue Print

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

Module 11 The C++ I/O System

Objects and streams and files CS427: Elements of Software Engineering

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

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

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

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

CLASS XII SECOND TERM EXAMINATION SUBJECT : COMPUTER SCIENCE SET A1(SOLUTIONS)

COMP322 - Introduction to C++

Fundamentals of Programming Session 28

Chapter 3 - Notes Input/Output


KENDRIYA VIDYALAYA SANGATHAN ERNAKULAM REGION FIRST PRE-BOARD EXAMINATION COMPUTER SCIENCE

Chapter 12 File Operations. Starting Out with C++, 3 rd Edition

Streams - Object input and output in C++

Transcription:

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 level, is interpreted simply as a sequence of (or stream of) bytes. Files in computers are of two types. One that stores instruction for the computer, i.e. a program file and the second that stores data, i.e. data file. FILES Program Files Date Files Text Files Binary Files data stored in the form of data stored in the form of characters (ASCII Code) sequence of bytes, i.e. 0 s & 1 s each line terminated with a special Character known as end-of-line there is no EOL character (EOL) character -------------------- What is a Stream? A stream is a general name given to the flow of data. Different streams are used to represent different kind of data flow. Each stream is associated with a particular class of fstream.h header file of the standard library. The streams are of the following types: Type of stream input stream (Read mode) output stream (Write mode) input/output stream (R/W mode) Associated Class ifstream ofstream fstream --------------------------- Basic Operations on A Text File Creating or writing in file. Reading a text file and displaying contents. Manipulating the contents read from a text file. To be able to carry out the above basic operations on a file, the following sequence has to be followed: Open the file. Perform operation on the file. Close the file. Opening A File Before opening a file, we shall create a file stream object of a particular class (ifstream, ofstream or fstream) depending upon the type of operation. e.g. In order to open a file as an input file i.e. data will be read from it and no other operation would take place, we shall create a file stream object of ifstream type. Page 1

Similarly, in order to open an output file (on which no operation can take place except writing only), we shall create a file stream object of ofstream type. A file can be opened in two ways: Using the constructor function of the class (useful when we use only one file in the stream) e.g. ofstream outfile( marks.txt ); Using member function open() of the class (useful in case of multiple files) e.g. ofstream outfile; outfile.open( marks.txt ); -------------------------------- Concept of File Modes The file mode describes how a file is to be used - to read from it, to write to it, to append it, and so on. File Mode Constants Meaning Associated Class ios::in Open for reading (default for ifstream) ifstream ios::out Open for writing (default for ofstream) ofstream ios::ate Start reading or writing at the end of file (AT End) ofstream ifstream ios::app Start writing at end of file (APPend) ofstream ios::trunk Truncate file to zero length if it exists (TRUNCate) ofstream ios::nocreate Error when opening if file does not already exist. ofstream ios::noreplace Error when opening for output if file already exist, unless ate or app is set. ofstream ios::binary Open file in binary (not text) mode. ofstream ifstream Note: 1) We can combine two or more file mode constants using the C++ bitwise OR ( ) operator. 2) The fstream class does not a mode by default and, therefore, one must specify the mode explicitly when using an object of the fstream class. ------------------------------------ How is end-of-file detected in a file? The end of any file is checked with eof() function which is predefined in class ios of ifstream, ofstream and fstream classes. If the file pointer points to the end-of-file then condition is TRUE and the object returns zero otherwise it returns a non-zero value. File Pointers Each file has two pointers associated with it which are called file pointers. One of them is the input pointer, known as get pointer; and the other one is called output pointer or the put pointer. File Pointers get pointer (input pointer) put pointer (output pointer) Used for reading the contents of a file location Used for writing to a given file location NOTE: Each time an input or output operation takes place; the concerned pointer is automatically advanced. Page 2

Open for reading only Open in app mode Open for writing only I N D I A I N D I A GET POINTER PUT POINTER PUT POINTER ------------------------------------------- How can the file pointers be moved in a file? The file stream classes support some predefined functions that navigate the position of the filepointers. The relevant functions are: seekg(), seekp(), tellg(), and tellp(). Function name seekg() seekp() tellg() tellp() Description Moves the get pointer or input pointer to a specified location Moves the put pointer or the output pointer to a specified ocation Gives the current position of the get pointer Gives the current position of the put pointer seekg() and seekp() are the functions used for manipulation of file pointers. e.g. ifile.seekg(30); This statement moves the get pointer to the byte number 30 in the file linked with ifile. Remember the counting of bytes in a file begins from zero. Another form of seek() function seekg( offset, reposition); seekp( offset, reposition); e.g. ifile.seekg(10, ios::beg); ifile.seekg(10, ios::cur); ifile.seekg(0, ios::end); //goto byte number 10 from the beginning //goto byte number 10 from the current position //goto end of the file. ifile.seekg(-10, ios::end) // goto 10 bytes before the end of file. Closing A File A file is closed by disconnecting it with the stream it is associated with. A file can be closed in two ways: If the file has been opened using constructor, it gets closed automatically as soon as the stream objects go out of scope. This calls the destructor, which closes the file. Using close function of the class e.g. infile.close(); (or) outfile.close(); ------------------------------------------- ------------------------------------------- Page 3

DATA FILE HANDLING (Previous Year Ques) 1) Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekp() and seekg() functions for performing the required task. #include <fstream.h> class Item int Ino;char Item[20]; public: //Function to search and display the content from a particular //record number void Search(int ); //Function to modify the content of a particular record number void Modify(int); ; void Item::Search(int RecNo) fstream File; File.open( STOCK.DAT,ios::binary ios::in); //Statement 1 File.read((char*)this,sizeof(Item)); cout<<ino<< ==> <<Item<<endl; File.close(); void Item::Modify(int RecNo) fstream File; File.open( STOCK.DAT,ios::binary ios::in ios::out); cout>>ino;cin.getline(item,20); //Statement 2 File.write((char*)this,sizeof(Item)); File.close(); File.seekg(RecNo*sizeof(Item)); //Statement 1 File.seekp(RecNo*sizeof(Item)); //Statement 2 ---------------------------------------------------------- 2) Observe the program segment given below carefully, and answer the question that follows : class PracFile int Pracno ; char PracName[20] int TimeTaken ; int Marks ; public : void EnterPrac( ); //Function to enter PracFile details void ShowPrac( ); //Function to display PracFile details int RTime( ) //function to return Time Taken return TimeTaken; void Assignmarks(int M) //Function to assign Marks Marks = M ; ; void AllocateMarks( ) fstream File ; File.open ( MARKS.DAT, ios :: binary l ios :: in l ios :: out ) ; PracFile P ; int Record = 0 ; while (File.read ( (char*) &P, sizeof (P) ) ) if (P.RTime( ) > 50) P.Assignmarks(0); else P.Assignmarks(10); //statement1 // statement2 Record++ ; File. close( ) ; If the function AllocateMarks( ) is supposed to Allocate Marks for the records in the file MARKS.DAT based on their value of the member TimeTaken. Write C++ statements for the statement1 and statement2,where statement 1 is required to position the file write pointer to an appropriate place in the file and statement 2 is to perform the write operation with the modified record. File.seekp(File.tellp()-sizeof(P)); //Statement 1 //File.seekp(Record*sizeof(P)); File.write((char*)&P,sizeof(P)); //Statement 2 //File.write((char*)&P,sizeof(PracFile)); ---------------------------------------------------------------- 3) Observe the program segment given below carefully, and answer the question that follows : class candidate long Cid ; // Candidate s Id char CName[20] ; // Candidate s Name float Marks ; // Candidate s Marks public ; void Enter( ) ; void Display( ) ; void MarksChange( ) ; // to change marks long R_Cid( ) return Cid ; ; void MarksUpdate (long Id) fstream File ; File.open ( CANDIDATE.DAT, ios :: binary ios::in ios :: out) ; Candidate C ; int Record = 0, Found = 0 ; while (!Found &&File.read((char*)&C, sizeof(c))) if (Id = =C.R_Cid( )) cout << Enter new Marks ; C.MarksChange( ) ; //statement 1 //statement 2 Found = 1 ; Record++ ; if (Found = = 1) cout << Record Updated ; File.close( ) ; Page 4

Write the Statement to position the File Pointer at the beginning of the Record for which the Candidate s Id matches with the argument passed, and Statement 2 to write the updated Record at that position. File.seekp(File.tellp( )-sizeof(c)); //Statement 1 //File.seekp(Record*sizeof(C)); File.write((char*)&C, sizeof(c)); //Statement 2 ------------------------------------------ 4) Find the output of the following C++ code considering that the binary file MEMBER.DAT exists on the hard disk with the records of 44 members. class MEMBER long Mno; char name[20]; public: void In(); void Out(); ; void main() fstream f; f.open( MEMBER.DAT, ios:: binary ios:: in); Member M; f.read((char*)&m, sizeof(m)); f.read((char*)&m, sizeof(m)); f.read((char*)&m, sizeof(m)); int POSITION = f.tellg()/ sizeof(m); cout<< present record: <<POSITION; cout<<endl; f.close(); present record:3 ----------------------------------------------------------------- 5) Write a function in C++ to count the number of lines present in a text file STORY.TXT void CountLine() ifstream FIL; FIL.open( STORY.TXT ); int LINES=0; char STR[80]; while (FIL.getline(STR,80)) LINES++; cout<< No. of Lines: <<LINES<<endl; FIL.close(); 6) Write a function in C++ to count the number of uppercase alphabets present in a text file ARTICLE.TXT. void UpperLetters( ) ifstream fin; fin.open("article.txt"); char ch; int ucnt=0; fin.get(ch); if(isupper(ch)) ucnt++; cout<<"\ntotal number of Uppercase alphabets in the file: "<<ucnt; ------------------------------------------ 7) Write a function to count the number of words present in a text file named PARA.TXT. Assume that each word is separated by a single blank/space character and no blanks/spaces in the beginning and end of the file. void WordCount( ) ifstream fin; Fin.open("PARA.TXT"); char word[20]; int count=1; cout<< Can t open the file ; fin.getline(word, 20, ); // space bar as delimiter character count++; cout<<"\ntotal number of Words in the file:" <<count; OR void WordCount( ) ifstream fin("para.txt"); char ch; int count=1; cout<< Can t open the file ; fin.get(ch); if(ch= = ) // space character count++; cout<<"total number of Words:"<<count; 8) Write a function in C++ to count the number of lines that starts with a uppercase letter from a text file ESSAY.TXT void CountLine() ifstream fin; fin.open( STORY.TXT ); Page 5

int count=0; char str[80]; fin.getline(str,80); if(isupper(str[0])) count++; cout<< No. of Lines that starts with uppercase letter: <<count<<endl; 9) Write a function in C++ to search for a BookNo from a binary file BOOK.DAT, assuming the binary file is containing the objects of the following class. class BOOK int Bno; char Title[20]; public: int RBno()return Bno; void Enter()cin>>Bno;gets(Title); void Display()cout<<Bno<<Title<<endl; ; void BookSearch() BOOK B; int bn, found=0; fstream fin; fin.open( BOOK.DAT,ios::binary); cout<< File can t be opened! ; cout<< Enter Book Num to search ; cin>>bn; while (fin.read((char*)&b, sizeof(b))) if (B.RBno()==bn) found++; B.Display(); if (found==0) cout<< Sorry! Book not found!!! <<endl; 10) Given a binary file TELEPHON.DAT, containing records of the following class Directory : class Directory char Name[20] ; char Address[30] ; char AreaCode[5] ; char phone_no[15] ; public ; void Register( ) ; void Show( ) ; int CheckCode(char AC[ ]) return strcmp(areacode, AC) ; ; 11) Write a function COPYABC( ) in C++, that would copy all those records having AreaCode as 123 from TELEPHON.DAT to TELEBACK.DAT. void COPYABC( ) ifstream fin( TELEPHON.DAT, ios::binary); ofstream fout( TELEBACK.DAT, ios::binary ios::app); Directory D; // or while(!fin.eof( )) fin.read((char*)&d, sizeof(d)); if(d.checkcode( 123 )= = 0) fout.write((char*)&d, sizeof(d)); fin.close( ); fout.close( ); 12) Given a binary file GAME.DAT, containing records of the following structure type struct Game char GameName[20] ; char Participate[10][30] ; ; Write a function in C++ that would read contents from the file GAME.DAT and creates a file named BASKET.DAT copying only those records from GAME.DAT where the game name is Basket Ball. void BPlayers( ) Game G; ifstream fin( GAME.DAT, ios::binary); ofstream fout( BASKET.DAT,ios::app ios::binary); cout<< File can t be opened! ; // or while(!fin.eof( )) fin.read((char*)&g, sizeof(g)); if(strcmpi(g.gamename, Basket Ball )== 0) fout.write((char*) &G, sizeof(g)); fin.close( ); fout.close( ); 13) Given a binary file SPORTS.DAT,containg records of the following structure type: struct Sports char Event[20] ; char Participant[10][30] ; ; Write a function in C++ that would read contents from the file SPORTS.DAT and creates a file named ATHLETIC.DAT copying only those records from SPORTS.DAT where the event name is Athletics. Page 6

void AthletesList( ) Sports S; ifstream fin( SPORTS.DAT, ios::binary); ofstream fout( ATHLETIC.DAT,ios::app ios::binary); cout<< File can t be opened! ; // or while(!fin.eof( )) fin.read((char*)&s,sizeof(sports)); if(strcmp(s.event, Athletics )== 0) fout.write((char*)&s,sizeof(s)); fin.close( ); fout.close( ); 14) Following is the structure of each record in a data file named COLONY.DAT struct COLONY char Colony_Code[10] ; char Colony_Name[10] int No_of_People ; ; Write a function in C++ to update the file with a new value of No_of_People. The value of Colony_Code and No_of_People are read during the execution of the program. void Update( ) COLONY C; fstream finout; finout.open( COLONY.DAT,ios::binary ios:: in ios::out); finout.seekg(0); while(finout) finout.read((char *)&C, sizeof(c)); cout<< \nthe Colony Code is: << C.Colony_Code; cout<< \nthe Colony Name is <<C.Colony_Name; cout<< \nenter the Number of People ; cin>>c.no_of_people; finout.seekp(finout.tellg()-sizeof(c)); finout.write((char *)&C,sizeof(C)); Page 7