ENG2139 Lecture 5
ENG2139 Lecture 5
ENG2139 Lecture 5
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.
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
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.
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");
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:
// 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;
}
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
• 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.
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;
25