Lecture 04 Files
Lecture 04 Files
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.
6
File formats and Extension
7
File Name and Extension Examples
8
Why files are needed?
When the C++ program is terminated, the entire
data is lost.
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;
11
Physical Files and Logical Files
Physical file: a collection of bytes stored on a
disk or tape.
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
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
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 (|)
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::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
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.
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();
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;}
}
Binary Files
Binary files contain data that is unformatted, and
not necessarily stored as ASCII text.
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.close();
}
53
Random Access Files
#include<iostream>
#include<fstream>
using namespace std;
void main()
{
ofstream outFile;
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
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.
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.
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.
71