Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views70 pages

Lecture 04 Files

The document outlines a summer course curriculum covering topics such as arrays, pointers, structures, classes, GUI, files, and strings, culminating in an exam. It details the concept of files in C++, including their types, formats, and the process of file input/output operations. Additionally, it explains the use of various functions and methods for reading from and writing to files, as well as handling errors and managing multiple files.

Uploaded by

abodiab100100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views70 pages

Lecture 04 Files

The document outlines a summer course curriculum covering topics such as arrays, pointers, structures, classes, GUI, files, and strings, culminating in an exam. It details the concept of files in C++, including their types, formats, and the process of file input/output operations. Additionally, it explains the use of various functions and methods for reading from and writing to files, as well as handling errors and managing multiple files.

Uploaded by

abodiab100100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Summer Course content

First Week:
 First Day: Arrays & Pointers
 Second Day: Structure & Classes
Second Week:
 Third Day: GUI
 Fourth Day: File & Strings
Third Week:
Fourth Week:
 Exam.(Sunday- 27/8/2017)

2
Summer Training

Files
Streams
C++ I/O occurs in streams, which are
sequences of bytes.

In input operations, the bytes flow from a


device (e.g., a keyboard, a disk drive, a
network connection, etc.) to main memory.

In output operations, the bytes flow from main


memory to a device (e.g., a display screen, a
printer, a disk drive, a network connection,
etc.). 4
Files
5
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.
 All files are assigned a name that is used for
identification purposes by the operating system and
the user.

6
File formats and Extension

7
File Name and Extension Examples

File Name and Extension File Contents


MYPROG.BAS BASIC program
MENU.BAT DOS Batch File
INSTALL.DOC Documentation File
CRUNCH.EXE Executable File
BOB.HTML HTML (Hypertext Markup Language) File
3DMODEL.JAVA Java program or applet
INVENT.OBJ Object File
PROG1.PRJ Borland C++ Project File
ANSI.SYS System Device Driver

README.TXT Text File

8
Why files are needed?
 When the C++ program is terminated, the entire
data is lost.

 If you want to keep large amount of data, it is time


consuming to enter the entire data every time you
run the C++ program.

 But, if a file is created, these information can be


accessed using few commands.

9
The Process of Using a File
 Using a file in a program is a simple four-step
process:
1) Create object from class “fstream”:
Fstream object_Name;

1) The file must be opened. If the file does not yet


exits, opening it means creating it.

2) Information is then saved to the file, read from the


file, or both.

3) When the program is finished using the file, the


file must be closed. 10
Writing/Reading data to/from file

11
Physical Files and Logical Files
 Physical file: a collection of bytes stored on a
disk or tape.

 logical file: a "channel" (like a telephone line) that


connects the program to a physical file.

 The program (application) sends (or receives) bytes


to (from) a file through the logical file. The
program knows nothing about where the bytes go
(came from).
12
Physical Files and Logical Files
 The operating system is responsible for associating a logical
file in a program to a physical file stored in a disk or tape.

 Writing to or reading from a file in a program is done


through the operating system.

 The physical file has a name, for instance myfile.txt

 The logical file has a logical name used for referring to the
file inside the program. This logical name is a variable
inside the program, for instance outfile

13
Physical Files and Logical Files
Access a file stored in a disk

C++
Program myfile.txt

14
Physical Files and Logical Files
Access a file stored in a disk

C++
Program myfile.txt

Logical Physical
Filename Input/output Stream
Filename
15
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 a header file


called “fstream.h”

16
Opening a File
 Before data can be written to or read from a file, the
file must be opened.

Logical
Filename Physical
Filename
ifstream inputFile;
inputFile.open(“c:\\customer.dat”);

17
ifstream vs ofstream

File Object Default Open Mode


Type
ofstream The file is opened for output only. (Information may be written
to the file, but not read from the file.) If the file does not exist,
it is created. If the file already exists, its contents are deleted
(the file is truncated).
ifstream The file is opened for input only. (Information may be read from
the file, but not written to it.) The file’s contents will be read
from its beginning. If the file does not exist, the open function
fails.
fstream The file is opened for input and output but, you have to specify
the file mode flag.

18
Opening a File Program
// This program demonstrates the declaration of an fstream
// object and the opening of a file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream outFile(“data.txt”); // Declare file stream object and open
the file
// or
ofstream outFile;
outFile.open(“data.txt”);

19
Opening a File using fstream
Logical
Physical bitwise
Filename
Filename operator OR (|)

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

File Mode
Flag

20
File Mode Flag
File Mode Meaning
Flag

ios::in Input mode. Information will be read from the file. If the
file does not exist, it will not be created and the open
function will fail.
ios::out Output mode. Information will be written to the file. By
default, the file’s contents will be deleted if it already
exists.
ios::app Append mode. If the file already exists, its contents are
preserved and all output is written to the end of the file.
By default, this flag causes the file to be created if it does
not exist.
ios::trunc If the file already exists, its contents will be deleted
(truncated). This is the default mode used by ios::out. 21
File Mode Flag
File Mode Meaning
Flag

ios::binary Binary mode. When a file is opened in binary mode,


information is written to or read from it in pure binary
format. (The default mode is text.)

ios::ate If the file already exists, the program goes directly to the
end of it. Output may be written anywhere in the file.
ios::nocreate If the file does not already exist, this flag will cause the
open function to fail. (The file will not be created.)
ios::noreplaceIf the file already exists, this flag will cause the open
function to fail. (The existing file will not be opened.)

22
Opening a File Program
// This program demonstrates the declaration of an fstream
// object and the opening of a file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream dataFile; // Declare file stream object
//open the file
dataFile.open(“inputdata.txt”, ios::out |ios::app );
cout << "The file was opened.\n";
dataFile.close();
}
Output:
The file was opened.

23
Opening a File Program
// This program demonstrates the declaration of an fstream
// object and the opening of a file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream dataFile; // Declare file stream object
char fileName[81];
cout << "Enter the name of a file you wish to open or create: ";
cin.getline(fileName, 81);
dataFile.open(fileName, ios::in);
cout << "The file " << fileName << " was opened.\n";
}
Output:
Enter the name of a file you wish to open
or create: mystuff.dat [Enter]
The file mystuff.dat was opened. 24
Testing for Open Errors

function output

is_open() Returns true if a file is open and associated with this


stream object. false otherwise.
bad() Returns true if a reading or writing operation fails.

fail() Returns true in the same cases as bad(), but also in


the case that a format error happens, like when an
alphabetical character is extracted when we are
an integer number trying to read.
eof() Returns true if a file open for reading has reached the end.

good() Returns true only if all the previous functions return


false. If one of them return true it return false

25
Testing for Open Errors
dataFile.open(“cust.dat”, ios::in);
if (!dataFile) //dataFile contains pointer to an object(NULL ≡ 0)
{
cout << “Error opening file.\n”;
exit(0);
}
 Another way to Test for Open Errors:

dataFile.open(“cust.dat”, ios::in);
if (dataFile.is_open())
cout << "Output operation successfully performed\n";
else
cout << "Error opening file";

26
Closing a File
 A file should be closed after finishing the use
of it.
dataFile.close();

27
Closing a File Program
// This program demonstrates the close function.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
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"; Output:
File was created successfully.
dataFile.close(); Now closing the file.
} 28
Using << to Write Data to a File
 The stream insertion operator (<<) may be
used to write information to a file.

outputFile << “I love C++ programming !”

29
Write Data to a File Program
// This program uses the << operator to write information to a file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream dataFile;
char line[81];
dataFile.open(“seqFile.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 << “Ahmed\n";
dataFile << “Mohamed\n";
dataFile << “Amer\n";
dataFile << “Mostafa\n";
dataFile.close();
cout << "Done.\n"; } 30
Append Data to a File Program
// This program writes information to a file, closes the file,
// then reopens it and appends more information.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream dataFile;
dataFile.open("demofile.txt", ios::out);
dataFile << “amer\n";
dataFile << “ahamed\n";
dataFile.close();
dataFile.open("demofile.txt", ios::app);
dataFile << “sara\n";
dataFile << “fatma\n";
dataFile.close();
} 32
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();

 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.
33
Reading Data from a File till eof
// This program uses the file stream object's eof() member
// function to detect the end of the file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
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"; 34
}
getline Function
dataFile.getline(str, size, Delimiter like:‘\n’);
 str – This is the name of a character array, or a pointer., The
information read from the file will be stored here.

 size – This number is one greater than the maximum number


of characters to 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 delimiter.)

35
Reading Data using getline function
// This program uses the file stream object's getline member
// function to read a line of information from the file.

#include <iostream>
#include <fstream>
using namespace std;
void main()
{
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())
{
nameFile.getline(input, 81); // use \n as a delimiter
cout << input << endl;
}
nameFile.close();
} 36
The get Function
inFile.get(ch);
// This program asks the user for a file name. The file is opened and
// its contents are readed character by character and finally displayed on the screen.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
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;
}
file.get(ch); // Get a character
while (!file.eof())
{
cout << ch;
file.get(ch); // Get another character }
file.close(); 37
}
The put Function
outFile.put(ch);
// This program demonstrates the put member function.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
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)
{ Program Screen Output with Example Input
cin.get(ch); Type a sentence and be sure to end it with a
period.
dataFile.put(ch); I am on my way to becoming a great programmer.
if (ch == '.') [Enter]
break;
} Resulting Contents of the File SENTENCE.TXT:
dataFile.close(); I am on my way to becoming a great
}
programmer.

38
Working with Multiple Files
 It’s possible to have more than one file open at once in a program
// This program demonstrates reading from one file and writing to a second file.
#include <iostream>
#include <fstream>
#include <ctype.h> // Needed for the toupper function
using namespace std;
void main()
{
ifstream inFile;
ofstream outFile("out.txt");
char fileName[81], ch, ch2;
cout << "Enter a file name: ";
cin >> fileName;
inFile.open(fileName);
39
Working with Multiple Files
if (!inFile)
{
cout << "Cannot open " << fileName << endl;
return;}

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"; 40

}
Binary Files
 Binary files contain data that is unformatted, and
not necessarily stored as ASCII text.

file.open(“stuff.dat”, ios::out | ios::binary);


write ( memory_block, size );
read ( memory_block, size );
Where :
memory_block is of type char* (pointer to char), and represents the address
of an array of bytes where the read data elements are stored or from where
the data elements to be written are taken.
The size parameter is an integer value that specifies the number of
characters to be read or written from/to the memory block

41
Write Function
// This program uses the write and read functions.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
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();
}

42
Creating Records with Structures`
 Structures may be used to store fixed-length records
to a file.
struct Info
{
char name[51];
int age;
char address[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.

43
Writing a Structure in a file
// This program demonstrates the use of a structure variable to
// store a record of information to a file.
#include <iostream>
#include <fstream>
#include <ctype.h> // for toupper
using name spacestd;
// Declare a structure for the record.
struct Info
{
char name[51];
int age;
char address[51];
char phone[14];
}; 44
Writing a Structure in a file
void main()
{
fstream people("people.dat", ios::out | ios::binary);
Info person;
char again;
if (!people)
{
cout << "Error opening file. Program
aborting.\n";
return;
}
45
Writing a Structure in a file
do
{ cout << "Enter the following information about a
”<< "person:\n";
cout << "Name: ";
cin.getline(person.name, 51);
cout << "Age: ";
cin >> person.age;
cin.ignore(); // skip over remaining newline.
cout << "Address : ";
cin.getline(person.address1, 51);
cout << "Phone: ";
cin.getline(person.phone, 14);
46
}
Writing a Structure in a file
people.write((char*)&person, sizeof(person));
cout << "Do you want to enter another record? ";
cin >> again;
cin.ignore();
} while (toupper(again) == 'Y');
people.close();
}// end of the program

47
Writing a Structure in a file
Program Screen Output with Example Input :
Enter the following information about a person:
Name: Charlie Baxter [Enter]
Age: 42 [Enter]
Address: 67 Kennedy Bvd. [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: 487 Lindsay Lane [Enter]
Phone: (704)453-9999 [Enter]
Do you want to enter another record? N [Enter]

48
Read a Structure from a file
fstream people("people.dat", ios::in | ios::binary);
Info person;

if (!people)
{
cout << "Error opening file. Program aborting.\n";
return;
}
int i = 1;
people.read((char *)&person, sizeof(person));
while (!people.eof())
{
cout << "Information about the " << i << " person:\n";
cout << "Name: " << person.name << endl;
cout << "Age: " << person.age << endl;
cout << "Address : " << person.address << endl;
cout << "Phone: " << person.phone << endl;
i++;
people.read((char *)&person, sizeof(person));
49
}
50
Accessing data stored in Files
 Sequential Access means accessing information in
a file one by one .
 Random Access means accessing information in a
file randomly.

51
Sequential Access Files
//sequential access file
#include<iostream>
#include<fstream>
using namespace std;
void main()
{
ofstream outFile;

outFile.open("SeqFile.txt");
int x = 5;
double y = 5.23;
char * z = "abc de";
cout << "Data before sent to file :\n" << "x = " << x << "\ty = " << y << "\tz = " << z << "\n";
outFile << x << " " << y << " " << z << "\n";

x = 6;
y = 1.25;
z = "abc ef g";
cout << "Data before sent to file :\n" << "x = " << x << "\ty = " << y << "\tz = " << z << "\n";
outFile << x << " " << y << " " << z << "\n";

outFile.close(); 52
Sequential Access Files
ifstream inFile;

inFile.open("SeqFile.txt");
int xFile;
double yFile;
char zFile[10];
char space;
inFile >> xFile >> yFile;
inFile.get(space);
inFile.getline(zFile, 10, '\n');
cout << "Data from file :\n" << "x = " << xFile << "\ty = " << yFile << "\tz = " << zFile
<< "\n";

inFile >> xFile >> yFile;


inFile.get(space);
inFile.getline(zFile, 10, '\n');
cout << "Data from file :\n" << "x = " << xFile << "\ty = " << yFile << "\tz = " << zFile
<< "\n";

inFile.close();
}
53
Random Access Files
#include<iostream>
#include<fstream>
using namespace std;
void main()
{
ofstream outFile;

outFile.open("RanmFile.txt", ios::binary | ios::trunc);


int x = 5;
double y = 5.23;
char z[10] = "abc de";
cout << "Data before sent to file :\n" << "x = " << x << "\ty = " << y << "\tz = " << z << "\n";
outFile.write((char*)&x, sizeof(x)).write((char*)&y, sizeof(y)).write((char*)z, sizeof(z));

x = 7;
y = 7.25;
char z1[10] = "abc ef g";
cout << "Data before sent to file :\n" << "x = " << x << "\ty = " << y << "\tz = " << z1 << "\n";
outFile.write((char*)&x, sizeof(x)).write((char*)&y, sizeof(y)).write((char*)z1,
sizeof(z1));

outFile.close(); 54
Random Access Files
ifstream inFile;

inFile.open("RanmFile.txt", ios::binary);
int xFile;
double yFile;
char zFile[10];

inFile.read((char*)&xFile, sizeof(xFile)).read((char*)&yFile,
sizeof(yFile)).read((char*)zFile, sizeof(zFile));
cout << "Data from file :\n" << "x = " << xFile << "\ty = " << yFile << "\tz = " << zFile << "\n";

inFile.read((char*)&xFile, sizeof(xFile)).read((char*)&yFile,
sizeof(yFile)).read((char*)zFile, sizeof(zFile));
cout << "Data from file :\n" << "x = " << xFile << "\ty = " << yFile << "\tz = " << zFile << "\n";

inFile.close();

55
Put and get pointers Mode Flag

put and get Description


pointers Mode
Flag
ios::beg The offset is calculated from the beginning of the
file.
ios::end The offset is calculated from the end of the file.
ios::cur The offset is calculated from the current position.

56
Seekp and seekg Functions
Statement How it Affects the Read/Write
Position
file.seekp(32L, ios::beg); Sets the write position to the 33rd byte (byte 32) from
the beginning of the file.
file.seekp(-10L, ios::end); Sets the write position to the 11th byte (byte 10) from
the end of the file.
file.seekp(120L, ios::cur); Sets the write position to the 121st byte (byte 120)
from the current position.
file.seekg(2L, ios::beg); Sets the read position to the 3rd byte (byte 2) from the
beginning of the file.
file.seekg(-100L, Sets the read position to the 101st byte (byte 100) from
ios::end); the end of the file.
file.seekg(40L, ios::cur); Sets the read position to the 41st byte (byte 40) from
the current position.
file.seekg(0L, ios::end); Sets the read position to the end of the file.
file.seekp(32L, ios::beg); Sets the write position to the 33rd byte (byte 32) from
the beginning of the file.
57
A Program on seekg function
fstream file("letters.txt", ios::in);
char ch;

file.seekg(5L, ios::beg);
file.get(ch);
cout << "Byte 5 from beginning: " << ch << endl;
file.get(ch);
cout << "Read the next Byte: " << ch << endl;
file.seekg(-10L, ios::end);
file.get(ch);
cout << "Byte 10 from end: " << ch << endl;
file.seekg(3L, ios::cur);
file.get(ch);
cout << "Byte 3 from current: " << ch << endl;
file.get(ch);
cout << "Read more one Byte from current: " << ch << endl;
file.close();

58
Updating Sequential Files
 Data that is formatted and written to a sequential file as
shown cannot be modified without the risk of destroying
other data in the file.
 The problem is that, in the formatted input/output model
using the stream insertion operator << and the stream
extraction operator >>,fields—and hence records—can vary
in size.
 For example, values 7,14,–117,2074,and 27383 are all ints,
which store the same number of “raw data” bytes internally
(typically four bytes on today’s popular 32-bit machines).
 However, these integers become different sized fields when
output as formatted text(character sequences).
 Therefore, the formatted input/output model usually is not
59
used to update records in place.
Updating Random Access Files
//Try to updata y in first record
fstream file;
file.open("RanmFile.txt", ios::binary | ios::in | ios::out);
int recordsize = sizeof(x) + sizeof(y) + sizeof(z);
file.seekp((sizeof(x)), ios::beg);
double yupdata = 10.921;
file.write((char*)&yupdata, sizeof(yupdata));
//Try to updata z in second record
int record_num = 2;
file.seekp(((record_num - 1) * recordsize) + (sizeof(x) + sizeof(y)), ios::beg);
char zupdata[10] = "ahmed";
file.write((char*)zupdata, sizeof(zupdata));
file.close();
//Print data from file after updata
inFile.open("RanmFile.txt", ios::binary);
inFile.read((char*)&xFile, sizeof(xFile)).read((char*)&yFile, sizeof(yFile)).read((char*)zFile,
sizeof(zFile));
cout << "Data from file :\n" << "x = " << xFile << "\ty = " << yFile << "\tz = " << zFile << "\n";
inFile.read((char*)&xFile, sizeof(xFile)).read((char*)&yFile, sizeof(yFile)).read((char*)zFile,
sizeof(zFile));
cout << "Data from file :\n" << "x = " << xFile << "\ty = " << yFile << "\tz = " << zFile << "\n";
inFile.close(); 60
Before

After

61
The tellp and tellg 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.

62
A Program on tellg function
// This program demonstrates the tellg function.
#include <iostream>
#include <fstream>
#include <ctype> // For toupper
using namespace std;
void main()
{ 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;
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();
} 63
A Program on tellg function
Program Screen 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
Do it again? y [Enter]
Currently at position 1
Enter an offset from the beginning of the file: 20
[Enter]
Character read: u
Do it again? n [Enter]
64
Opening a File for Input/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);

65
Opening File for Input/output program
// This program sets up a file of inventory records.
#include <iostream.>
#include <fstream.>
using namespace std;
// Declaration of Inventory structure Output on screen
struct Inventory Now writing record 0
{ Now writing record 1
char item[31];
Now writing record 2
Now writing record 3
int quantity;
Now writing record 4
float price;
};
void main()
{
fstream inv("invtry.dat", ios::out | ios::binary);
Inventory record = { “Laptop", 1, 5000.0 };
// Now write the blank records
for (int count = 0; count < 5; count++)
{
cout << "Now writing record " << count << endl;
inv.write((char *)&record, sizeof(record));
} inv.close(); 66
}
Opening File for Input/output program
// This program displays the contents of the inventory file.
#include <iostream.h>
#include <fstream.h>
// Declaration of Inventory structure
void main()
{
fstream inv("invtry.dat", ios::in | ios::binary);
Inventoryrecord = { "", 0, 0.0 };
// Now read and display the records
inv.read((char *)&record, sizeof(record));
while (!inv.eof())
{
cout << "Description: ";
cout << record.item << endl;
cout << "Quantity: ";
cout << record.quantity << endl;
cout << "Price: ";
cout << record.price << endl << endl;
inv.read((char *)&record, sizeof(record));
}
inv.close(); 67
}
Opening File for Input/output program
// This program allows the user to edit a specific record in the inventory file.
#include <iostream.h>
#include <fstream.h>
// Declaration of Inventory structure
void main()
{
fstream inv("invtry.dat", ios::in | ios::out | ios::binary);
Inventory record; int recNum;
cout << "Which record do you want to edit?";
cin >> recNum;
inv.seekg(recNum * sizeof(record), ios::beg);
inv.read((char *)&record, sizeof(record));
cout << "Description: " << record.item << endl;
cout << "Quantity: "<< record.quantity << endl;
cout << "Price: " << record.price << endl;
cout << "Enter the new data:\n";
cout << "Description: ";

68
Opening File for Input/output program
cin.ignore();
cin.getline(record.item, 31);
cout << "Quantity: ";
cin >> record.qtuantity;
cout << "Price: ";
cin >> record.price;
inv.seekp(recNum * sizeof(record), ios::beg);
inv.write((char *)&record, sizeof(record));
inv.close();
}

69
Passing File to Functions
 File stream objects are passed by reference to
functions.

int openFileIn(fstream &file, char name[51])


{
file.open(name, ios::in);
if (file.fail())
return 0;
return 1;
}
70
Thank You

71

You might also like