ENG2139 Lecture 5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

ENG2139 INTRODUCTION TO ICT

Lecture 5 : Using Files for data storage

Instructor: George ZIBA


Email: [email protected]
0976854627

George ZIBA , DEPT. of EEE, School of Engineering, UNZA


References
Our main reference text books and websites in this course are:
[1] Juan Soulie, 2007, C++ Language Tutorial
[2] Tony Gaddis, 2015, Starting out with C++ from control structures through
objects
[3] https://www.w3schools.com/cpp/

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 2


Course Outline
Introduction and Basics of C++ :Syntax, Output, Comments, Structure of a program,
Variables, Data types, Constants, Basic input/output, Operators, Strings, Booleans,
Math, Conditions, Switch, While Loop, For Loop, Break/Continue, Arrays, Structures,
References, Pointers

C++ Functions: Functions, Function Parameters, Function Overloading, Recursion,


variable scope

Characters and C-Strings: Character Testing, Character Case Conversion, C-Strings,


Library Functions for Working with C-Strings, C-String/Numeric Conversion
Functions, More About the C++ string Class

Using files for data storage:

C++ Classes: OOP, Classes/Objects, Class Methods, Constructors, Access Specifiers,


Encapsulation, Inheritance, Polymorphism, Exceptions

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 5


3
Using Files for Data Storage
• When a program needs to save data for later use, it writes the data
in a file. The data can then be read from the file at a later time
• The programs you have written so far require the user to reenter
data each time the program runs, because data kept in variables
and control properties is stored in RAM and disappears once the
program stops running.
• If a program is to retain data between the times it runs, it must
have a way of saving it.
• Data is saved in a file, which is usually stored on a computer’s disk.
• Once the data is saved in a file, it will remain there after the
program stops running.

4
• Programmers usually refer to the process of saving
data in a file as writing data to the file.
• When a piece of data is written to a file, it is copied
from a variable in RAM to the file
• An output file is a file that data is written to. It is
called an output file because the program stores
output in it.
• The process of retrieving data from a file is known as
reading data from the file
• An input file is a file that data is read from. It is
called an input file because the program gets input
from the file.
5
• When a file is used by a program, three steps must be
taken:
1. Open the file— Opening a file creates a connection
between the file and the program. Opening an output
file usually creates the file on the disk and allows the
program to write data to it. Opening an input file
allows the program to read data from the file.
2. Process the file— Data is either written to the file (if it
is an output file) or read from the file (if it is an input
file).
3. Close the file— After the program is finished using
the file, the file must be closed. Closing a file
disconnects the file from the program.
6
Types of Files
• In general, there are two types of files: text and binary. A
text file contains data that has been encoded as text,
using a scheme such as ASCII or Unicode.
• Even if the file contains numbers, those numbers are
stored in the file as a series of characters.
• As a result, the file may be opened and viewed in a text
editor such as Notepad.
• A binary file contains data that has not been converted
to text. Thus, you cannot view the contents of a binary
file with a text editor. In this course we work only with
text files.
7
File Access Methods
• There are two general ways to access data stored in a file:
sequential access and direct access.
• When you work with a sequential access file , you access
data from the beginning of the file to the end of the file.
• If you want to read a piece of data that is stored at the very
end of the file, you have to read all of the data that comes
before it—you cannot jump directly to the desired data.

• When you work with a random access file (also known as a


direct access file ), you can jump directly to any piece of data
in the file without reading the data that comes before it.

8
Filenames and File Stream Objects
• Files on a disk are identified by a filename . For
example, when you create a document with a word
processor and then save the document in a file, you
have to specify a filename.
• Each operating system has its own rules for naming
files.
• Many systems, including Windows, support the use
of filename extensions , which are short sequences
of characters that appear at the end of a filename
preceded by a period
9
• In order for a program to work with a file on the
computer’s disk, the program must create a file stream
object in memory.
• A file stream object is an object that is associated with
a specific file and provides a way for the program to
work with that file.
• File stream objects work very much like the cin and
cout objects. A stream of data may be sent to cout ,
which causes values to be displayed on the screen.
• A stream of data may be read from the keyboard by
cin , and stored in variables. Likewise, streams of data
may be sent to a file stream object, which writes the
data to a file.
10
Setting Up a Program for File Input/Output

• Just as cin and cout require the iostream file to be


included in the program, C++ file access requires
another header file. The file fstream contains all the
declarations necessary for file operations. It is
included with the following statement
• #include <fstream>
• The fstream header file defines the data types
ofstream , ifstream , and fstream . Before a C++
program can work with a file, it must define an
object of one of these data types.
11
ofstream Output file stream. You create an object of this data
type when you want to create a file and write data to
it.

ifstream Input file stream. You create an object of this data type
when you want to open an existing file and read data
from it.

fstream File stream. Objects of this data type can be used to


open files for reading, writing, or both.

12
Create and Write To a File
• To create a file, use either the ofstream or fstream class, and specify the
name of the file.
• To write to the file, use the insertion operator (<<)

#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}
13
ofstream outputFile;
outputFile.open("Employees.txt");

• The first statement defines an ofstream object named outputFile . The


second statement calls the object’s open member function, passing
the string "Employees.txt" as an argument.
• In this statement, the open member function creates the
Employees.txt file and links it with the outputFile object.
• After this code executes, you will be able to use the outputFile object
to write data to the Employees.txt file. It’s important to remember
that when you call an ofstream object’s open member function, the
specified file will be created. If the specified file already exists, it will
be erased, and a new file with the same name will be created.
• Often, when opening a file, you will need to specify its path as well as
its name. For example, on a Windows system the following statement
opens the file:
inputFile.open("C:\\data\\inventory.txt")

14
Read a File
• To read from a file, use either the ifstream or fstream class, and the name of the file.
• Note that we also use a while loop together with the getline() function (which
belongs to the ifstream class) to read the file line by line, and to print the content of
the file:

// Create a text string, which is used to output the text file


string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();

15
The Read Position
• When a file has been opened for input, the file stream object
internally maintains a special value known as a read position .
• A file’s read position marks the location of the next byte that
will be read from the file. When an input file is opened, its
read position is initially set to the first byte in the file.
• So, the first read operation extracts data starting at the first
byte. As data is read from the file, the read position moves
forward, toward the end of the file.
• Keep in mind that when the >> operator extracts data from a
file, it expects to read pieces of data that are separated by
whitespace characters (spaces, tabs, or newlines).

16
Reading Numeric Data From a Text File
• Remember that when data is stored in a text file, it is
encoded as text, using a scheme such as ASCII or
Unicode. Even if the file contains numbers, those
numbers are stored in the file as a series of characters.
• For example, suppose a text file contains numeric
data, the numbers are stored in the file as the strings
"10" , "20" , and "30" . Fortunately, you can use the >>
operator to read data such as this from a text file, into
a numeric variable, and the >> operator will
automatically convert the data to a numeric data type.

17
Using Loops to Process Files
• Although some programs use files to store
only small amounts of data, files are typically
used to hold large collections of data. When a
program uses a file to write or read a large
amount of data, a loop is typically involved.

18
// This program reads data from a file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream outputFile; // File stream object
int numberOfDays; // Number of days of sales
double sales; // Sales amount for a day

// Get the number of days.


cout << "For how many days do you have sales? ";
cin >> numberOfDays;

// Open a file named Sales.txt.


outputFile.open("Sales.txt");

// Get the sales for each day and write it


// to the file.
for (int count = 1; count <= numberOfDays; count++)
{
// Get the sales for a day.
cout << "Enter the sales for day "
<< count << ": ";
cin >> sales;

// Write the sales to the file.


outputFile << sales << endl;
}

// Close the file.


outputFile.close();
cout << "Data written to Sales.txt\n";
return 0;
19
}
Detecting the End of the File
• Quite often a program must read the contents of a file without knowing the number
of items that are stored in the file. For example, suppose you need to write a
program that displays all of the items in a file, but you do not know how many items
the file contains.

• You can open the file and then use a loop to repeatedly read an item from the file
and display it. However, an error will occur if the program attempts to read beyond
the end of the file.

• The program needs some way of knowing when the end of the file has been reached
so it will not try to read beyond it. Fortunately, the >> operator not only reads data
from a file, but also returns a true or false value indicating whether the data was
successfully read or not. If the operator returns true, then a value was successfully
read. If the operator returns false, it means that no value was read from the file.

while (inputFile >> number)

20
Testing for File Open Errors
• Under certain circumstances, the open member
function will not work. For example, the following
code will fail if the file info.txt does not exist:
ifstream inputFile;
inputFile.open("info.txt");
• There is a way to determine whether the open
member function successfully opened the file.
• After you call the open member function, you can
test the file stream object as if it were a Boolean
expression.
21
//This program tests for file open errors.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
int number;

// Open the file.


inputFile.open("BadListOfNumbers.txt");

// If the file successfully opened, process it.


if (inputFile)
{
// Read the numbers from the file and
// display them.
while (inputFile >> number)
{
cout << number << endl;
}
// Close the file.
inputFile.close();
}
else
{
// Display an error message.
cout << "Error opening the file.\n";
}
return 0;
}
22
Letting the User Specify a Filename
• In each of the previous examples, the name of
the file that is opened is hard-coded as a string
literal into the program.
• In many cases, you will want the user to
specify the name of a file for the program to
open.
• In C++ 11, you can pass a string object as an
argument to a file stream object’s open
member function.
23
// This program lets the user enter a filename.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
string filename;
int number;
// Get the filename from the user.
cout << "Enter the filename: ";
cin >> filename;
// Open the file.
inputFile.open(filename);
// If the file successfully opened, process it.
if (inputFile)
{
// Read the numbers from the file and
// display them.
while (inputFile >> number)
{
cout << number << endl;
}

// Close the file.


inputFile.close();
}
else
{
// Display an error message.
cout << "Error opening the file.\n";
}
return 0;
}
24
End of Lecture 5

Thank you for your attention!

25

You might also like