binary file handling - insert, delete,modify
TRANSCRIPT
Starting Out with C++, 3rd Edition1
Chapter 12 – File Operations
Starting Out with C++, 3rd Edition2
12.1 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.
Starting Out with C++, 3rd Edition3
12.2 File Names
• All files are assigned a name that is used for identification purposes by the operating system and the user.
Starting Out with C++, 3rd Edition4
Table 12-1File Name and Extension File Contents
M Y P R O G .B A S BASIC program
M E N U .B A T DOS Batch File
IN S T A L L .D O C Documentation File
C R U N C H .E X E Executable File
B O B .H T M L HTML (Hypertext Markup Language) File
3 D M O D E L .JA V A Java program or applet
IN V E N T .O B J Object File
P R O G 1 .P R J Borland C++ Project File
A N S I.S Y S System Device Driver
R E A D M E .T X T Text File
Starting Out with C++, 3rd Edition5
12.3 Focus on Software Engineering: 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.
Starting Out with C++, 3rd Edition6
Figure 12-1
Starting Out with C++, 3rd Edition7
Figure 12-2
Starting Out with C++, 3rd Edition8
12.4 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
Starting Out with C++, 3rd Edition9
12.5 Opening a File
• Before data can be written to or read from a file, the file must be opened.
ifstream inputFile;inputFile.open(“customer.dat”);
Starting Out with C++, 3rd Edition10
Program 12-1// 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 objectchar 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";
}
Starting Out with C++, 3rd Edition11
Program Output with Example Input
Enter the name of a file you wish to openor create: mystuff.dat [Enter]The file mystuff.dat was opened.
Starting Out with C++, 3rd Edition12
Table 12-3
File Type Default Open Modeo fs tre a m The file is opened for output only. (Information may be
written to the file, but not read from the file.) If the filedoes not exist, it is created. If the file already exists, itscontents are deleted (the file is truncated).
ifs tre a m The file is opened for input only. (Information may beread from the file, but not written to it.) The file’scontents will be read from its beginning. If the file doesnot exist, the open function fails.
Starting Out with C++, 3rd Edition13
Table 12-4File Mode Flag Meaningio s ::ap p Append mode. If the file already exists, its
contents are preserved and all output iswritten to the end of the file. By default, thisflag causes the file to be created if it doesnot exist.
io s ::a te If the file already exists, the program goesdirectly to the end of it. Output may bewritten anywhere in the file.
io s ::b in a ry Binary mode. When a file is opened inbinary mode, information is written to orread from it in pure binary format. (Thedefault mode is text.)
io s ::in Input mode. Information will be read fromthe file. If the file does not exist, it will notbe created and the open function will fail.
Starting Out with C++, 3rd Edition14
Table 12-4 continuedFile ModeFlag
Meaning
io s ::n o crea te If the file does not already exist, this flagwill cause the open function to fail. (The filewill not be created.)
io s ::n o rep lace If the file already exists, this flag will causethe open function to fail. (The existing filewill not be opened.)
io s ::o u t Output mode. Information will be written tothe file. By default, the file’s contents willbe deleted if it already exists.
io s ::tru n c If the file already exists, its contents will bedeleted (truncated). This is the defaultmode used by ios::out.
Starting Out with C++, 3rd Edition15
Opening a File at Declaration
fstream dataFile(“names.dat”, ios::in | ios::out);
Starting Out with C++, 3rd Edition16
Program 12-2
// 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";
}
Starting Out with C++, 3rd Edition17
Program Output with Example Input
The file names.dat was opened.
Starting Out with C++, 3rd Edition18
Testing for Open Errors
dataFile.open(“cust.dat”, ios::in); if (!dataFile){ cout << “Error opening file.\n”;}
Starting Out with C++, 3rd Edition19
Another way to Test for Open Errors
dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()){ cout << “Error opening file.\n”;}
Starting Out with C++, 3rd Edition20
12.6 Closing a File
• A file should be closed when a program is finished using it.
Starting Out with C++, 3rd Edition21
Program 12-3// 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();
}
Starting Out with C++, 3rd Edition22
Program Output
File was created successfully.Now closing the file.
Starting Out with C++, 3rd Edition23
12.7 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 !”
Starting Out with C++, 3rd Edition24
Program 12-4// 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;}
Starting Out with C++, 3rd Edition25
Program continues
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";
}
Starting Out with C++, 3rd Edition26
Program Screen Output
File opened successfully.Now writing information to the file.Done.
Output to File demofile.txtJonesSmithWillisDavis
Starting Out with C++, 3rd Edition27
Figure 12-3
Starting Out with C++, 3rd Edition28
Program 12-5// 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";dataFile.close();
}
Starting Out with C++, 3rd Edition29
Output to File demofile.txt
JonesSmithWillisDavis
Starting Out with C++, 3rd Edition30
12.8 File Output Formatting
• File output may be formatted the same way as screen output.
Starting Out with C++, 3rd Edition31
Program 12-6// 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;
}
Starting Out with C++, 3rd Edition32
Program continues
dataFile << num << endl;dataFile.precision(5);dataFile << num << endl;dataFile.precision(4);dataFile << num << endl;dataFile.precision(3);dataFile << num << endl;
}
Starting Out with C++, 3rd Edition33
Contents of File numfile.txt
123.456123.46123.5124
Starting Out with C++, 3rd Edition34
Program 12-7#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 numbersfor (int row = 0; row < 3; row++){for (int col = 0; col < 3; col++){
outFile << setw(4) << nums[row][col] << " ";}outFile << endl;}outFile.close();
}
Starting Out with C++, 3rd Edition35
Contents of File TABLE.TXT
2897 5 837 34 7 1623 390 3456 12
Starting Out with C++, 3rd Edition36
Figure 12-6
Starting Out with C++, 3rd Edition37
12.9 Using >> to Read Information from a File
• The stream extraction operator (>>) may be used to read information from a file.
Starting Out with C++, 3rd Edition38
Program 12-8// 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";
Starting Out with C++, 3rd Edition39
Program continues
for (int count = 0; count < 4; count++){
dataFile >> name;cout << name << endl;
}dataFile.close();cout << "\nDone.\n";
}
Starting Out with C++, 3rd Edition40
Program Screen Output
File opened successfully.Now reading information from the file.
JonesSmithWillisDavis
Done.
Starting Out with C++, 3rd Edition41
12.10 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();
Starting Out with C++, 3rd Edition42
Program 12-9// 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";
Starting Out with C++, 3rd Edition43
Program continues
dataFile >> name; // Read first name from the filewhile (!dataFile.eof()){
cout << name << endl;dataFile >> name;
}dataFile.close();cout << "\nDone.\n";
}
Starting Out with C++, 3rd Edition44
Program Screen Output
File opened successfully.Now reading information from the file.
JonesSmithWillisDavisDone.
Starting Out with C++, 3rd Edition45
Note on eof()
• In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. The eof() function returns true when there is no more information to be read.
Starting Out with C++, 3rd Edition46
12.11 Passing File Stream Objects to Functions• File stream objects may be passed by reference to
functions.bool openFileIn(fstream &file, char name[51]){ bool status;
file.open(name, ios::in); if (file.fail()) status = false; else status = true; return status;}
Starting Out with C++, 3rd Edition47
12.12 More Detailed Error Testing
• All stream objects have error state bits that indicate the condition of the stream.
Starting Out with C++, 3rd Edition48
Table 12-5
Bit Descriptionio s::eo fb it Set when the end of an input stream is
encountered.io s ::fa ilb it Set when an attempted operation has failed.io s ::h a rd fa il Set when an unrecoverable error has occurred.io s ::b a d b it Set when an invalid operation has been
attempted.io s ::g o o d b it Set when all the flags above are not set.
Indicates the stream is in good condition.
Starting Out with C++, 3rd Edition49
Table 12-6Function Descriptioneo f() Returns true (non-zero) if the eofbit flag is set,
otherwise returns false.fa il() Returns true (non-zero) if the failbit or hardfail
flags are set, otherwise returns false.b ad () Returns true (non-zero) if the badbit flag is set,
otherwise returns false.g o o d () Returns true (non-zero) if the goodbit flag is
set, otherwise returns false.c lea r() When called with no arguments, clears all the
flags listed above. Can also be called with aspecific flag as an argument.
Starting Out with C++, 3rd Edition50
Program 12-11// This program demonstrates the return value of the stream// object error testing member functions.#include <iostream.h> #include <fstream.h>// Function prototypevoid showState(fstream &);
void main(void){
fstream testFile("stuff.dat", ios::out);if (testFile.fail()){cout << "cannot open the file.\n";return;}
Starting Out with C++, 3rd Edition51
Program continues
int num = 10;cout << "Writing to the file.\n";testFile << num; // Write the integer to testFileshowState(testFile);testFile.close(); // Close the filetestFile.open("stuff.dat", ios::in); // Open for inputif (testFile.fail()){
cout << "cannot open the file.\n";return;
}
Starting Out with C++, 3rd Edition52
Program continuescout << "Reading from the file.\n";testFile >> num; // Read the only number in the fileshowState(testFile);cout << "Forcing a bad read operation.\n";testFile >> num; // Force an invalid read operationshowState(testFile);testFile.close(); // Close the file
}
// Definition of function ShowState. This function uses// an fstream reference as its parameter. The return values of// the eof(), fail(), bad(), and good() member functions are // displayed. The clear() function is called before the function// returns.
Starting Out with C++, 3rd Edition53
Program continues
void showState(fstream &file){
cout << "File Status:\n";cout << " eof bit: " << file.eof() << endl;cout << " fail bit: " << file.fail() << endl;cout << " bad bit: " << file.bad() << endl;cout << " good bit: " << file.good() << endl;file.clear(); // Clear any bad bits
}
Starting Out with C++, 3rd Edition54
Program OutputWriting to the file.File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1Reading from the file.File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1Forcing a bad read operation.File Status: eof bit: 1 fail bit: 2 bad bit: 0 good bit: 0
Starting Out with C++, 3rd Edition55
12.13 Member Functions for Reading and Writing Files
• File stream objects have member functions for more specialized file reading and writing.
Starting Out with C++, 3rd Edition56
Figure 12-8
Starting Out with C++, 3rd Edition57
Program 12-12// 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;
}
Starting Out with C++, 3rd Edition58
Program 12-12 (continued)
nameFile >> input;while (!nameFile.eof()){
cout << input;nameFile >> input;
}nameFile.close();
}
Starting Out with C++, 3rd Edition59
Program Screen Output
JayneMurphy47JonesCircleAlmond,NC28702
Starting Out with C++, 3rd Edition60
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.)
Starting Out with C++, 3rd Edition61
Program 12-13// 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)//if name file not present on disk{
cout << "File open error!" << endl;return;
}
Starting Out with C++, 3rd Edition62
Program continues
nameFile.getline(input, 81); // use \n as a delimiterwhile (!nameFile.eof()){
cout << input << endl;nameFile.getline(input, 81); // use \n as a
delimiter}nameFile.close();
}
Starting Out with C++, 3rd Edition63
Program Screen Output
Jayne Murphy47 Jones CircleAlmond, NC 28702
Starting Out with C++, 3rd Edition64
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())//whether data file end not come {
cout << input << endl;dataFile.getline(input, 81, '$');
}dataFile.close();
}
Starting Out with C++, 3rd Edition65
Program Output
Jayne Murphy47 Jones CircleAlmond, NC 28702
Bobbie Smith217 Halifax DriveCanton, NC 28716
Bill HammetPO Box 121Springfield, NC 28357
Starting Out with C++, 3rd Edition66
The get Member Function
inFile.get(ch);
Starting Out with C++, 3rd Edition67
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;
}
Starting Out with C++, 3rd Edition68
Program continues
file.get(ch); // Get a characterwhile (!file.eof()){
cout << ch;file.get(ch); // Get another character
}file.close();
}
Starting Out with C++, 3rd Edition69
The put Member Function
• outFile.put(ch);
Starting Out with C++, 3rd Edition70
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();
}
Starting Out with C++, 3rd Edition71
Program Screen Output with Example Input
Type a sentence and be sure to end it with aperiod.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.
Starting Out with C++, 3rd Edition72
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.
Starting Out with C++, 3rd Edition73
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;}
Starting Out with C++, 3rd Edition74
Program continuesinFile.get(ch); // Get a characer from file 1while (!inFile.eof()) // Test for end of file{
ch2 = toupper(ch); // Convert to uppercaseoutFile.put(ch2); // Write to file2
inFile.get(ch); // Get another character from file 1}inFile.close();outFile.close();cout << "File conversion done.\n";
}
Starting Out with C++, 3rd Edition75
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?
Starting Out with C++, 3rd Edition76
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);
Starting Out with C++, 3rd Edition77
Figure 12-9
Starting Out with C++, 3rd Edition78
Figure 12-10
Starting Out with C++, 3rd Edition79
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] << " ";file.close();
}
Starting Out with C++, 3rd Edition80
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
Starting Out with C++, 3rd Edition81
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.
Starting Out with C++, 3rd Edition82
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];
};
Starting Out with C++, 3rd Edition83
Program continuesvoid 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: ";
Starting Out with C++, 3rd Edition84
Program continuescin.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;
} while (toupper(again) == 'Y');people.close();
}
Starting Out with C++, 3rd Edition85
Program Screen Output with Example InputEnter 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]Enter the following information about a person: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]
Starting Out with C++, 3rd Edition86
12.17 Random Access Files
• Random Access means non-sequentially accessing informaiton in a file.
Figure 12-11
Starting Out with C++, 3rd Edition87
Table 12-7Mode Flag Description
io s ::b e g The offset is calculated fromthe beginning of the file.
io s ::en d The offset is calculated fromthe end of the file.
io s ::cu r The offset is calculated fromthe current position.
Starting Out with C++, 3rd Edition88
Table 12-8
Statement How it Affects the Read/Write Position
F ile .seek p (3 2 L , io s::b e g ); Sets the write position to the 33rd byte (byte 32) from the beginning of the file.
file .see k p (-1 0 L , io s::en d ); Sets the write position to the 11th byte (byte 10) from the end of the file.
file .see k p (1 2 0 L , io s ::cu r) ; Sets the write position to the 121st byte (byte 120) from the current position.
file .see k g (2 L , io s::b eg ); Sets the read position to the 3rd byte (byte 2) from the beginning of the file.
file .see k g (-1 0 0 L , io s::en d ); Sets the read position to the 101st byte (byte 100) from the end of the file.
file .see k g (4 0 L , io s ::cu r); Sets the read position to the 41st byte (byte 40) from the current position.
file .see k g (0 L , io s::en d ); Sets the read position to the end of the file.
Starting Out with C++, 3rd Edition89
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);file.get(ch);cout << "Byte 10 from end: " << ch << endl;
Starting Out with C++, 3rd Edition90
Program continues
file.seekg(3L, ios::cur);file.get(ch);cout << "Byte 3 from current: " << ch << endl;file.close();
}
Starting Out with C++, 3rd Edition91
Program Screen Output
Byte 5 from beginning: fByte 10 from end: qByte 3 from current: u
Starting Out with C++, 3rd Edition92
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.
Starting Out with C++, 3rd Edition93
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;
Starting Out with C++, 3rd Edition94
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();
}
Starting Out with C++, 3rd Edition95
Program Output with Example Input
Currently at position 0Enter an offset from the beginning of the file: 5 [Enter]Character read: fDo it again? y [Enter]Currently at position 6Enter an offset from the beginning of the file: 0 [Enter]Character read: aDo it again? y [Enter]Currently at position 1Enter an offset from the beginning of the file: 20 [Enter]Character read: uDo it again? n [Enter]
Starting Out with C++, 3rd Edition96
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);
Starting Out with C++, 3rd Edition97
Program 12-24// This program sets up a file of blank inventory records.#include <iostream.h>#include <fstream.h>
// Declaration of Invtry structurestruct Invtry{
char desc[31];int qty;float price;
}; void main(void){
fstream inventory("invtry.dat", ios::out | ios::binary);Invtry record = { "", 0, 0.0 };
Starting Out with C++, 3rd Edition98
Program continues
// Now write the blank recordsfor (int count = 0; count < 5; count++){
cout << "Now writing record " << count << endl;inventory.write((char *)&record, sizeof(record));
}inventory.close();
}
Starting Out with C++, 3rd Edition99
Program Screen Output
Now writing record 0Now writing record 1Now writing record 2Now writing record 3Now writing record 4
Starting Out with C++, 3rd Edition100
Program 12-25// This program displays the contents of the inventory file.#include <iostream.h>#include <fstream.h>
// Declaration of Invtry structurestruct Invtry{
char desc[31];int qty;float price;
};
void main(void){
fstream inventory("invtry.dat", ios::in | ios::binary);Invtry record = { "", 0, 0.0 };
Starting Out with C++, 3rd Edition101
Program continues// Now read and display the recordsinventory.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.read((char *)&record, sizeof(record));
}inventory.close();
}
Starting Out with C++, 3rd Edition102
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: 0Price: 0.0Description:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0Description:Quantity: 0Price: 0.0
Starting Out with C++, 3rd Edition103
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 structurestruct Invtry{
char desc[31];int qty;float price;
};
void main(void){
Starting Out with C++, 3rd Edition104
Program continuesfstream 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";cout << "Description: ";
Starting Out with C++, 3rd Edition105
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();
}
Starting Out with C++, 3rd Edition106
Program Screen Output with Example Input
Which record do you ant to edit? 2 [Enter]Description:Quantity: 0Price: 0.0Enter the new data:Description: Wrench [Enter]Quantity: 10 [Enter]Price: 4.67 [Enter]
Starting Out with C++, 3rd Edition
INSERTING DATA IN SORTED FILE
• To insert data in sorted file,firstly approprite position is determined,
• If record insert in mid of file then copy upper data from position in tempory files then insert new record. and copy the remaining record.
• If we want to insert record in first position then append new record at first position and append rest of record.
107
Starting Out with C++, 3rd Edition
• Similarly at last position do the same process.first determine the position and copy and append old data and then at last position append new records.
• Now our temporary file will be ready to save on hard disk.so first delete the old file that is save on hard disk.and place the tempory file on disk and rename it to original file.
• And close the file.
108
Starting Out with C++, 3rd Edition
• Include<fstream.h>• Include<stdio.h> // for rename and remove
• class student{ int rollno;• Char name[25];• Char class [4];• float marks;• Char grade;• Public :• Void getdata()• {cout<<“rollno.”<<“name”<<“class”<<“marks”;• Cin>>rollno>>name>>class>>marks;• if(marks>=75) grade =‘A’ else• If(marks>=60) grade=‘B’ else• else grade=‘f’;• }• Void putdata()• { cout<<rollno<<name<<marks<<grade<<endl; }• Void getrollno() {cout<< rollno ;} • }s1,stud;• to be continued…... 109
Starting Out with C++, 3rd Edition
• Void main()• { ifstream fin(“student.dat”,ios::in); / /student.dat must exist on disk • Ofstream fout(“temp.dat”,ios::out);• Char last=‘y’; //to determine whether new record• Cout<<“enter details of student whose record is to be inserted”;• S1.getdata;• While(!fin eof( ) ) //wheater end of file not coming • { fin.read ((char*) &student, sizeof(student));//read character of student and
load size of student file in memory• If (s1.getrollno()<=student.getrollno()); //then• fout.write((char*) & s1,sizeof(s1))• last=‘n’;• Break;• }• else• fout.write((char*)&student,sizeof(student));• } to be continued…….. 110
Starting Out with C++, 3rd Edition
• If(last= =‘y’) //if the next rollno greater than all rollnos in the file, then• fout.write ((char*)&s1,sizeof(s1));• Else if (!fin.eof())• {while(!fin.eof())• { fin. read((char*) & student, size of(student));• fout. write((char*) & student, size of(student));• }• fin.close();• fout.close();• remove(“student.dat”);• rename(“temp.dat”,student.dat)• fin.open(“student.dat); //a new file will be created on the hard disk• Cout<<“A new file now contains ”;• While(!fin.eof()) • break;• Student. putdata();• }• fin.close(); /file closed• } • 111
Starting Out with C++, 3rd Edition
• enter details of student whose record is to be inserted• Rollno-115• Name-ramesh• Class-12th
• Marks-88• File now contains:• Rollno-102 name-joseph marks-81 grade-B• Rollno-104 name-riya marks-88 grade-A• Rollno-105 name-simran marks-77 grade-B• Rollno-115 name-ramesh marks-88 grade-B
112
Starting Out with C++, 3rd Edition
DELETING AN EXISTING DATA FROM A FILE.
• TO Delete data from an existing file,it has to be removed physiccally from the file.this may be achive the steps given below:-
• The file is opened from the purpose of reading.• The user is asked to enter data to be deleted in a delete key.• Copy all data other than the one to be deleted into a temporary file.• Donot copy the data to be deleted.• Copy the remaining records of the file on the temporary
file(temp.dat).• Delete the original file.• Rename the temporary file. As that of deleted file.•
113
Starting Out with C++, 3rd Edition114
Starting Out with C++, 3rd Edition
Starting Out with C++, 3rd Edition116
Starting Out with C++, 3rd Edition117
Starting Out with C++, 3rd Edition118
Starting Out with C++, 3rd Edition119
Starting Out with C++, 3rd Edition120
Starting Out with C++, 3rd Edition121
Starting Out with C++, 3rd Edition122
Starting Out with C++, 3rd Edition
Modifying Data
• To modify a record, follow these steps:-• First file is opened in input/output mode• give the beginning address of record being
modified• After the record is modified in memory.the file
pointer is once again placed at the beginning position of the record.
• After that record is rerewitten.123