File Handling Operations in C++

Slides:



Advertisements
Similar presentations
Starting Out with C++, 3 rd Edition 1 Chapter 12 – File Operations.
Advertisements

STARTING OUT WITH STARTING OUT WITH Class 15 Honors.
Copyright © 2012 Pearson Education, Inc. Chapter 12: Advanced File Operations.
17 File Processing. OBJECTIVES In this chapter you will learn:  To create, read, write and update files.  Sequential file processing.  Random-access.
DATA FILE HANDLING. Contents to be covered in class  Concept of files & streams  Stream class hierarchy  File handling functions  Text V/S Binary.
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
1 File I/O In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
FILE HANDLING IN C++.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 12: Advanced File Operations.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
File handling in C++ BCA Sem III K.I.R.A.S. Using Input/Output Files Files in C++ are interpreted as a sequence of bytes stored on some storage media.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Starting Out with C++, 3 rd Edition 1 File Operations in C++
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
File I/O. fstream files File: similar to vector of elements Used for input and output Elements of file can be –character (text)struct –object (non-text.
I/O in C++ October 7, Junaed Sattar. Stream I/O a stream is a flow of bytes/characters/ints or any type of data input streams: to the program output.
C++ FILE I/O.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 13 File Input and.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 12 Advanced File Operations.
DCT1063 Programming 2 CHAPTER 3 FILE INPUT AND FILE OUTPUT Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba.
Starting Out with C++, 3 rd Edition 1 Chapter 12 – File Operations.
STARTING OUT WITH STARTING OUT WITH Class 16 Honors.
File Handling. Read data from file and display it on screen #include int main() { /* fin object is created with parameterzied constructor */ ifstream.
1 CSC241: Object Oriented Programming Lecture No 32.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Learners Support Publications Working with Files.
FILE HANDLING(WORKING WITH FILES) FILE- A file is a collection of related data stored in a particular area on the disk. STREAMS- interface between the.
Binary Files. Text Files vs. Binary Files Text files: A way to store data in a secondary storage device using Text representation (e.g., ASCII characters)
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
Data File Handling in C++ Data File Handling in C++ Paritosh Srivastava PGT (Comp. Science) Kendriya VidyalayaJoshimath.
Starting Out with C++ 1 Chapter 12: File Operations What is a File? A file is a collection on information, usually stored on some electronic medium. Information.
KBD Program with file I/O Operation File Disk Program with file I/O Operation Screen Cin Cout.
Ms N Nashandi Dr SH Nggada 2016/01/03Ms N Nashandi and Dr SH Nggada1 Week 6 -File input and output in C++
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
CS212: Object Oriented Analysis and Design
Chapter 14: Sequential Access Files
Programming with ANSI C ++
17 File Processing.
Tutorial4us.com File Handling in C++ Tutorial4us.com.
Data File Handling in C++
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Basic Input and Output Operations
Chapter 2 part #3 C++ Input / Output
FILE HANDLING IN C++.
Standard Input/Output Streams
Standard Input/Output Streams
File I/O with Records Lesson xx
files Dr. Bhargavi Goswami Department of Computer Science
Tutorial4us.com. File A file is a collection of related data stored in a particular area on the disk. The data is stored in disk using the concept of.
Topics Input and Output Streams More Detailed Error Testing
Chapter 12: Advanced File Operations.
Sindhu S PGT Comp.Sc. K V Kollam
Chapter 3 Input output.
Data File Handling in C++
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Data File Handling RITIKA SHARMA.
Chapter 2 part #3 C++ Input / Output
C++ Programming Lecture 8 File Processing
File I/O in C++ I.
Presentation transcript:

File Handling Operations in C++ Rakhee Chhibber

What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused. All files are assigned a name that is used for identification purposes by the operating system and the user.

The Process of Using a File Using a file in a program is a simple three-step process The file must be opened. If the file does not yet exits, opening it means creating it. Information is then saved to the file, read from the file, or both. When the program is finished using the file, the file must be closed.

Files in C++ 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 a component header file called fstream.h The I/O library manages two aspects- as interface and for transfer of data. The library predefine a set of operations for all file related handling through certain classes.

The fstream.h header file A stream is a general term used to name flow of data. Streams act as an interface between files and programs. A Stream is sequence of bytes. They represent as a sequence of bytes and deals with the flow of data. Every stream is associated with a class having member functions and operations for a particular kind of data flow. File  Program ( Input stream) - reads Program  File (Output stream) – write All designed into fstream.h and hence needs to be included in all file handling programs. Diagrammatically as shown in next slide

DISK FILE PROGRAM Output Stream Input Stream write data to file read data from file data output Output Stream Input Stream data input

File Handling Classes in C++ Hierarchy Diagram

FUNCTIONS OF FILE STREAM CLASSES filebuf – It sets the buffer to read and write, it contains close() and open() member functions on it. fstreambase – this is the base class for fstream and, ifstream and ofstream classes. therefore it provides the common function to these classes. It also contains open() and close() functions. ifstream – Being input class it provides input operations it inherits the functions get( ), getline( ), read( ), and random access functions seekg( ) and tellg( ) functions. ofstream – Being output class it provides output operations it inherits put( ), write( ) and random access functions seekp( ) and tellp( ) functions. fstream – it is an i/o class stream, it provides simultaneous input and output operations.

Setting Up a Program for File Input/Output Before file I/O can be performed, a C++ program must be set up properly. File access requires the inclusion of fstream.h Before data can be written to or read from a file, the file must be opened. ifstream inputFile; inputFile.open(“customer.dat”);

// This program demonstrates the declaration of an fstream // object and the opening of a file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; // Declare file stream object char fileName[81]; cout << "Enter the name of a file you wish to open\n"; cout << "or create: "; cin.getline(fileName, 81); dataFile.open(fileName, ios::out); cout << "The file " << fileName << " was opened.\n"; }

Program Output with Example Input Enter the name of a file you wish to open or create: mystuff.dat [Enter] The file mystuff.dat was opened.

fstream dataFile(“names.dat”, ios::in | ios::out);

Steps To Create A File 1. Declare an object of the desired file stream class(ifstream, ofstream, or fstream) 2. Open the required file to be processed using constructor or open function. 3. Process the file. 4. Close the file stream using the object of file stream.

eof ( ) Function This function determines the end-of-file by returning true(non-zero) for end of file otherwise returning false(zero). Syntax Stream_object.eof( ); Example : fout.eof( );

Text File Functions get() – read a single character from text file and store in a buffer. e.g file.get(ch); put() - writing a single character in textfile e.g. file.put(ch); getline() - read a line of text from text file store in a buffer. e.g file.getline(s,80); We can also use file>>ch for reading and file<<ch writing in text file. But >> operator does not accept white spaces.

Program to create a text file using strings I/O #include<fstream.h> //header file for file operations void main() { char s[80], ch; ofstream file(“myfile.txt”); //open myfile.txt in default output mode do { cout<<”\n enter line of text”; gets(s); //standard input file<<s; // write in a file myfile.txt cout<<”\n more input y/n”; cin>>ch; }while(ch!=’n’||ch!=’N’); file.close(); } //end of main

Program to read content of ‘myfile.txt’ and display it on monitor. #include<fstream.h> //header file for file operations void main() { char ch; ifstream file(“myfile.txt”); //open myfile.txt in default input mode while(file) { file.get(ch) // read a character from text file ‘ myfile.txt’ cout<<ch; // write a character in text file ‘myfile.txt ‘ } file.close(); } //end of main

Program Output with Example Input // This program demonstrates the opening of a file at the // time the file stream object is declared. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("names.dat", ios::in | ios::out); cout << "The file names.dat was opened.\n"; } Program Output with Example Input The file names.dat was opened.

Testing for Open Errors dataFile.open(“cust.dat”, ios::in); if (!dataFile) { cout << “Error opening file.\n”; } Closing a File A file should be closed when a program is finished using it.

Program Output File was created successfully. Now closing the file. // This program demonstrates the close function. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("testfile.txt", ios::out); if (!dataFile) cout << "File open error!" << endl; return; } cout << "File was created successfully.\n"; cout << "Now closing the file.\n"; dataFile.close(); Program Output File was created successfully. Now closing the file.

File TYPES A File can be stored in two ways Text File Binary File Text Files : Stores information in ASCII characters. In text file each line of text is terminated by with special character known as EOL (End of Line) In text file some translations takes place when this EOL character is read or written. Binary File: it contains the information in the same format as it is held in the memory. In binary file there is no delimiter for a line. Also no translation occur in binary file. As a result binary files are faster and easier for program to read and write.

Text files Using << to Write Information to a File The stream insertion operator (<<) may be used to write information to a file. outputFile << “I love C++ programming !”

// This program uses the << operator to write information to a file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; char line[81]; dataFile.open("demofile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now writing information to the file.\n"; dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile << "Willis\n"; dataFile << "Davis\n"; dataFile.close(); cout << "Done.\n"; }

Output to File demofile.txt Jones Smith Willis Davis Program Screen Output File opened successfully. Now writing information to the file. Done. Output to File demofile.txt Jones Smith Willis Davis

Output to File demofile.txt // This program writes information to a file, closes the file, // then reopens it and appends more information. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("demofile.txt", ios::out); dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile.close(); dataFile.open("demofile.txt", ios::app); dataFile << "Willis\n"; dataFile << "Davis\n"; } Output to File demofile.txt Jones Smith Willis Davis

File Output Formatting // This program uses the precision member function of a // file stream object to format file output. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; float num = 123.456; dataFile.open("numfile.txt", ios::out); if (!dataFile) cout << "File open error!" << endl; return; } dataFile << num << endl; dataFile.precision(5); dataFile.precision(4); dataFile.precision(3); dataFile << num << endl; } Contents of File numfile.txt 123.456 123.46 123.5 124

#include <iostream.h> #include <fstream.h> #include <iomanip.h> void main(void) { fstream outFile("table.txt", ios::out); int nums[3][3] = { 2897, 5, 837, 34, 7, 1623, 390, 3456, 12 }; // Write the three rows of numbers for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) outFile << setw(4) << nums[row][col] << " "; } outFile << endl; outFile.close(); } Contents of File TABLE.TXT 2897 5 837 34 7 1623 390 3456 12

Using >> to Read Information from a File The stream extraction operator (>>) may be used to read information from a file.

#include <iostream.h> // This program uses the >> operator to read information from a file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now reading information from the file.\n\n"; for (int count = 0; count < 4; count++) dataFile >> name; cout << name << endl; } dataFile.close(); cout << "\nDone.\n"; }

Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.

Detecting the End of a File The eof() member function reports when the end of a file has been encountered. if (inFile.eof()) inFile.close();

// This program uses the file stream object's eof() member // function to detect the end of the file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now reading information from the file.\n\n"; dataFile >> name; // Read first name from the file while (!dataFile.eof()) cout << name << endl; dataFile >> name; } dataFile.close(); cout << "\nDone.\n"; }

Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.

Member Functions for Reading and Writing Files File stream objects have member functions for more specialized file reading and writing.

File inside

JayneMurphy47JonesCircleAlmond,NC28702 // This program uses the file stream object's eof() member // function to detect the end of the file. #include <iostream.h> #include <fstream.h> void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; } nameFile >> input; while (!nameFile.eof()) { cout << input; } nameFile.close(); Program Screen Output JayneMurphy47JonesCircleAlmond,NC28702

The getline Member Function dataFile.getline(str, 81, ‘\n’); str – This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here. 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. ‘\n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘\n’ is the default.)

Program Screen Output Jayne Murphy 47 Jones Circle Almond, NC 28702 // This program uses the file stream object's getline member // function to read a line of information from the file. #include <iostream.h> #include <fstream.h> void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) cout << "File open error!" << endl; return; } nameFile.getline(input, 81); // use \n as a delimiter while (!nameFile.eof()) cout << input << endl; nameFile.getline(input, 81); // use \n as a delimiter nameFile.close();} Program Screen Output Jayne Murphy 47 Jones Circle Almond, NC 28702

Program 12-14 // This file shows the getline function with a user- // specified delimiter. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("names2.txt", ios::in); char input[81]; dataFile.getline(input, 81, '$'); while (!dataFile.eof()) cout << input << endl; dataFile.getline(input, 81, '$'); } dataFile.close();

Program Output Jayne Murphy 47 Jones Circle Almond, NC 28702 Bobbie Smith 217 Halifax Drive Canton, NC 28716 Bill Hammet PO Box 121 Springfield, NC 28357

The get Member Function inFile.get(ch);

Program 12-15 // This program asks the user for a file name. The file is // opened and its contents are displayed on the screen. #include <iostream.h> #include <fstream.h> void main(void) { fstream file; char ch, fileName[51]; cout << "Enter a file name: "; cin >> fileName; file.open(fileName, ios::in); if (!file) cout << fileName << “ could not be opened.\n"; return; }

Program continues file.get(ch); // Get a character while (!file.eof()) { cout << ch; file.get(ch); // Get another character } file.close();

The put Member Function outFile.put(ch);

Program 12-16 // This program demonstrates the put member function. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("sentence.txt", ios::out); char ch; cout << "Type a sentence and be sure to end it with a "; cout << "period.\n"; while (1) { cin.get(ch); dataFile.put(ch); if (ch == '.') break; } dataFile.close();

Program Screen Output with Example Input Type a sentence and be sure to end it with a period. I am on my way to becoming a great programmer. [Enter] Resulting Contents of the File SENTENCE.TXT: I am on my way to becoming a great programmer.

12.14 Focus on Software Engineering: Working with Multiple Files It’s possible to have more than one file open at once in a program.

Program 12-17 // This program demonstrates reading from one file and writing // to a second file. #include <iostream.h> #include <fstream.h> #include <ctype.h> // Needed for the toupper function void main(void) { ifstream inFile; ofstream outFile("out.txt"); char fileName[81], ch, ch2; cout << "Enter a file name: "; cin >> fileName; inFile.open(fileName); if (!inFile) { cout << "Cannot open " << fileName << endl; return; }

Program continues inFile.get(ch); // Get a characer from file 1 while (!inFile.eof()) // Test for end of file { ch2 = toupper(ch); // Convert to uppercase outFile.put(ch2); // Write to file2 inFile.get(ch); // Get another character from file 1 } inFile.close(); outFile.close(); cout << "File conversion done.\n";

Program Screen Output with Example Input Enter a file name: hownow.txt [Enter] File conversion done. Contents of hownow.txt: how now brown cow. How Now? Resulting Contents of out.txt: HOW NOW BROWN COW. HOW NOW?

12.15 Binary Files Binary files contain data that is unformatted, and not necessarily stored as ASCII text. file.open(“stuff.dat”, ios::out | ios::binary);

Figure 12-9

Figure 12-10

Program 12-18 // This program uses the write and read functions. #include <iostream.h> #include <fstream.h> void main(void) { fstream file(“NUMS.DAT", ios::out | ios::binary); int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "Now writing the data to the file.\n"; file.write((char*)buffer, sizeof(buffer)); file.close(); file.open("NUMS.DAT", ios::in); // Reopen the file. cout << "Now reading the data back into memory.\n"; file.read((char*)buffer, sizeof(buffer)); for (int count = 0; count < 10; count++) cout << buffer[count] << " "; }

Program Screen Output Now writing the data to the file. Now reading the data back into memory. 1 2 3 4 5 6 7 8 9 10

12.16 Creating Records with Structures Structures may be used to store fixed-length records to a file. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; }; Since structures can contain a mixture of data types, you should always use the ios::binary mode when opening a file to store them.

Program 12-19 // This program demonstrates the use of a structure variable to // store a record of information to a file. #include <iostream.h> #include <fstream.h> #include <ctype.h> // for toupper // Declare a structure for the record. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; };

Program continues void main(void) { fstream people("people.dat", ios::out | ios::binary); Info person; char again; if (!people) cout << "Error opening file. Program aborting.\n"; return; } do cout << "Enter the following information about a ” << "person:\n"; cout << "Name: ";

Program continues cin.getline(person.name, 51); cout << "Age: "; cin >> person.age; cin.ignore(); // skip over remaining newline. cout << "Address line 1: "; cin.getline(person.address1, 51); cout << "Address line 2: "; cin.getline(person.address2, 51); cout << "Phone: "; cin.getline(person.phone, 14); people.write((char *)&person, sizeof(person)); cout << "Do you want to enter another record? "; cin >> again; cin.ignore(); } while (toupper(again) == 'Y'); people.close(); }

Program Screen Output with Example Input Enter the following information about a person: Name: Charlie Baxter [Enter] Age: 42 [Enter] Address line 1: 67 Kennedy Bvd. [Enter] Address line 2: Perth, SC 38754 [Enter] Phone: (803)555-1234 [Enter] Do you want to enter another record? Y [Enter] Name: Merideth Murney [Enter] Age: 22 [Enter] Address line 1: 487 Lindsay Lane [Enter] Address line 2: Hazelwood, NC 28737 [Enter] Phone: (704)453-9999 [Enter] Do you want to enter another record? N [Enter]

12.17 Random Access Files Random Access means non-sequentially accessing informaiton in a file. Figure 12-11

Table 12-7

Table 12-8

Program 12-21 // This program demonstrates the seekg function. #include <iostream.h> #include <fstream.h> void main(void) { fstream file("letters.txt", ios::in); char ch; file.seekg(5L, ios::beg); file.get(ch); cout << "Byte 5 from beginning: " << ch << endl; file.seekg(-10L, ios::end); cout << "Byte 10 from end: " << ch << endl;

Program continues file.seekg(3L, ios::cur); file.get(ch); cout << "Byte 3 from current: " << ch << endl; file.close(); }

Program Screen Output Byte 5 from beginning: f Byte 10 from end: q Byte 3 from current: u

The tellp and tellg Member Functions tellp returns a long integer that is the current byte number of the file’s write position. tellg returns a long integer that is the current byte number of the file’s read position.

Program 12-23 // This program demonstrates the tellg function. #include <iostream.h> #include <fstream.h> #include <ctype.h> // For toupper void main(void) { fstream file("letters.txt", ios::in); long offset; char ch, again; do cout << "Currently at position " << file.tellg() << endl; cout << "Enter an offset from the beginning of the file: "; cin >> offset;

Program continues file.seekg(offset, ios::beg); file.get(ch); cout << "Character read: " << ch << endl; cout << "Do it again? "; cin >> again; } while (toupper(again) == 'Y'); file.close(); }

Program Output with Example Input Currently at position 0 Enter an offset from the beginning of the file: 5 [Enter] Character read: f Do it again? y [Enter] Currently at position 6 Enter an offset from the beginning of the file: 0 [Enter] Character read: a Currently at position 1 Enter an offset from the beginning of the file: 20 [Enter] Character read: u Do it again? n [Enter]

12.18 Opening a File for Both Input and Output You may perform input and output on an fstream file without closing it and reopening it. fstream file(“data.dat”, ios::in | ios::out);

Program 12-24 // This program sets up a file of blank inventory records. #include <iostream.h> #include <fstream.h> // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) fstream inventory("invtry.dat", ios::out | ios::binary); Invtry record = { "", 0, 0.0 };

Program continues // Now write the blank records for (int count = 0; count < 5; count++) { cout << "Now writing record " << count << endl; inventory.write((char *)&record, sizeof(record)); } inventory.close();

Program Screen Output Now writing record 0 Now writing record 1 Now writing record 2 Now writing record 3 Now writing record 4

Program 12-25 // This program displays the contents of the inventory file. #include <iostream.h> #include <fstream.h> // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) fstream inventory("invtry.dat", ios::in | ios::binary); Invtry record = { "", 0, 0.0 };

Program continues // Now read and display the records inventory.read((char *)&record, sizeof(record)); while (!inventory.eof()) { cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl << endl; } inventory.close();

Here is the screen output of Program 12-25 if it is run immediately after Program 12-24 sets up the file of blank records. Program Screen Output Description: Quantity: 0 Price: 0.0

Program 12-26 // This program allows the user to edit a specific record in // the inventory file. #include <iostream.h> #include <fstream.h> // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void)

Program continues fstream inventory("invtry.dat", ios::in | ios::out | ios::binary); Invtry record; long recNum; cout << "Which record do you want to edit?"; cin >> recNum; inventory.seekg(recNum * sizeof(record), ios::beg); inventory.read((char *)&record, sizeof(record)); cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl; cout << "Enter the new data:\n";

Program continues cin.ignore(); cin.getline(record.desc, 31); cout << "Quantity: "; cin >> record.qty; cout << "Price: "; cin >> record.price; inventory.seekp(recNum * sizeof(record), ios::beg); inventory.write((char *)&record, sizeof(record)); inventory.close(); }

Program Screen Output with Example Input Which record do you ant to edit? 2 [Enter] Description: Quantity: 0 Price: 0.0 Enter the new data: Description: Wrench [Enter] Quantity: 10 [Enter] Price: 4.67 [Enter]

1. Write a function in C++ to count the number of uppercase alphabets present in a text file “BOOK.txt”. 2. Write a function in C++ to count the number of alphabets present in a text file “BOOK.txt”. 3. Write a function in C++ to count the number of digits present in a text file “BOOK.txt”. 4. Write a function in C++ to count the number of white spaces present in a text file “BOOK.txt”. 5. Write a function in C++ to count the number of vowels present in a text file “BOOK.txt”. 6. Assume a text file “Test.txt” is already created. Using this file, write a function to create three files “LOWER.TXT” which contains all the lowercase vowels and “UPPER.TXT” which contains all the uppercase vowels and “DIGIT.TXT” which contains all digits.

Binary File Functions read( )- read a block of binary data or reads a fixed number of bytes from the specified stream and store in a buffer. Syntax : Stream_object.read((char *)& Object, sizeof(Object)); e.g file.read((char *)&s, sizeof(s)); write( ) – write a block of binary data or writes fixed number of bytes from a specific memory location to the specified stream. Syntax : Stream_object.write((char *)& Object, sizeof(Object)); e.g file.write((char *)&s, sizeof(s));

Binary File Functions Note: Both functions take two arguments. • The first is the address of variable, and the second is the length of that variable in bytes. The address of variable must be type cast to type char*(pointer to character type) • The data written to a file using write( ) can only be read accurately using read( ).

Program to create a binary file ‘student.dat’ using structure. #include<fstream.h> struct student { char name[15]; float percent; }; void main() ofstream fout; char ch; fout.open(“student.dat”, ios::out | ios:: binary); clrscr(); student s; if(!fout) cout<<“File can’t be opened”; exit(0); }

do { cout<<”\n enter name of student”; gets(s); cout<<”\n enter percentage”; cin>>percent; fout.write((char *)&s,sizeof(s)); // writing a record in a student.dat file cout<<”\n more record y/n”; cin>>ch; }while(ch!=’n’ || ch!=’N’); fout.close(); }

Program to read a binary file ‘student.dat’ display records on monitor. #include<fstream.h> struct student { char name[15]; float percent; }; void main() ifstream fin; student s; fin.open(“student.dat”,ios::in | ios:: binary); fin.read((char *) &s, sizeof(student)); //read a record from file ‘student.dat’ CONTD....

while(file) { cout<<s.name; cout<<“\n has the percent: ”<<s.percent; fin.read((char *) &s, sizeof(student)); } fin.close();

RELATED TO BINARY FILES 3 MARKS QNO 4 ( c ) CBSE QUESTION PATTERN RELATED TO BINARY FILES 3 MARKS QNO 4 ( c )

QNO 4 ( C ) Write a function in c++ to search for details (Phoneno and Calls) of those Phones which have more than 800 calls from binary file “phones.dat”. Assuming that this binary file contains records/ objects of class Phone, which is defined below. CBSE 2012 class Phone { Char Phoneno[10]; int Calls; public: void Get() {gets(Phoneno); cin>>Calls;} void Billing() { cout<<Phoneno<< “#”<<Calls<<endl;} int GetCalls() {return Calls;} };

Ans : void Search() { Phone P; fstream fin; fin.open( “Phone.dat”, ios::binary| ios::in); while(fin.read((char *)&P, sizeof(P))) if(p.GetCalls() >800) p.Billing(); } Fin.close(); //ignore }};

Write a function in C++ to add new objects at the bottom of a binary file “STUDENT.DAT”, assuming the binary file is containing the objects of the following class. class STUD { int Rno; char Name[20]; public: void Enter() {cin>>Rno;gets(Name);} void Display(){cout<<Rno<<Name<<endl;} };

Ans. void searchbook(int bookno) {ifstream ifile(“BOOK.DAT”,ios::in|ios::binary); if(!ifile) {cout<<”could not open BOOK.DAT file”; exit(-1);} else {BOOK b; int found=0; while(ifile.read((char *)&b, sizeof(b))) {if(b.RBno()==bookno) {b.Display(); found=1; break;} } if(! found) cout<<”record is not found “; ifile.close();

Given a binary file PHONE Given a binary file PHONE.DAT, containing records of the following class type class Phonlist { char name[20]; char address[30]; char areacode[5]; char Phoneno[15]; public: void Register() void Show(); void CheckCode(char AC[]) {return(strcmp(areacode,AC); }; Write a function TRANSFER( ) in C++, that would copy all those records which are having areacode as “DEL” from PHONE.DAT to PHONBACK.DAT.

Ans void TRANSFER() { fstream File1,File2; Phonelist P; File1.open(“PHONE.DAT”, ios::binary|ios::in); File2.open(“PHONEBACK.DAT”, ios::binary|ios::OUT) while(File1.read((char *)&P, sizeof(P))) { if( p.CheckCode( “DEL”)) File2.write((char *)&P,sizeof(P)); } File1.close(); File2.close(); }

File Pointer The file pointer indicates the position in the file at which the next input/output is to occur. Moving the file pointer in a file for various operations viz modification, deletion , searching etc. Following functions are used seekg(): It places the file pointer to the specified position in input mode of file. e.g file.seekg(p,ios::beg); or file.seekg(-p,ios::end), or file.seekg(p,ios::cur) i.e to move to p byte position from beginning, end or current position.

File Pointer seekp(): It places the file pointer to the specified position in output mode of file. e.g file.seekp(p,ios::beg); or file.seekp(-p,ios::end), or file.seekp(p,ios::cur) i.e to move to p byte position from beginning, end or current position. tellg(): This function returns the current working position of the file pointer in the input mode. e.g int p=file.tellg(); tellp(): This function returns the current working position of the file pointer in the output mode. e.f int p=file.tellp();

RELATED TO FILE POINTER 1 MARK QNO 4 ( a ) CBSE QUESTION PATTERN RELATED TO FILE POINTER 1 MARK QNO 4 ( a )

4(a) Observe the program segment carefully and answer the question that follows: class stock { int Ino, Qty; Char Item[20]; public: void Enter() { cin>>Ino; gets(Item); cin>>Qty;} void issue(int Q) { Qty+=0;} void Purchase(int Q) {Qty-=Q;} int GetIno() { return Ino;} };

void PurchaseItem(int Pino, int PQty) { fstream File; File.open(“stock.dat”, ios::binary|ios::in|ios::out); Stock s; int success=0; while(success= = 0 && File.read((char *)&s,sizeof(s))) { If(Pino= = ss.GetIno()) s.Purchase(PQty); _______________________ // statement 1 _______________________ // statement 2 Success++; }

if (success = =1) cout<< “Purchase Updated”<<endl; else cout<< “Wrong Item No”<<endl; File.close() ; }

Ans i) Statement 1 to position the file pointer to the appropriate place so that the data updation is done for the required item. File.seekp(File.tellg()-sizeof(stock); OR File.seekp(-sizeof(stock),ios::cur); ii) Staement 2 to perform write operation so that the updation is done in the binary file. File.write((char *)&s, sizeof(s)); OR File.write((char *)&s, sizeof(stock));