0% found this document useful (0 votes)
27 views

Chapter 4 File

This chapter discusses file input/output (I/O) in C++. It introduces file streams as a way to read from and write to files. The key types are ifstream for input files and ofstream for output files. Streams must be connected to files using open or by specifying the file in the stream's constructor before reading from or writing to the file. Common file I/O operations like reading and writing data are performed using the extraction and insertion operators similarly to keyboard/screen I/O.

Uploaded by

nuniyat.g
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Chapter 4 File

This chapter discusses file input/output (I/O) in C++. It introduces file streams as a way to read from and write to files. The key types are ifstream for input files and ofstream for output files. Streams must be connected to files using open or by specifying the file in the stream's constructor before reading from or writing to the file. Common file I/O operations like reading and writing data are performed using the extraction and insertion operators similarly to keyboard/screen I/O.

Uploaded by

nuniyat.g
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter Four

File Operations (File I/O)

1
Objectives

● This chapter aims for the students to


● Understand the need behind file io
● Understand input and output streams
● Connect streams to files
● Understand file access mode
● Read from and write to files
● Write C++ programs using file streams

Chapter 4: File Management 2


Introduction
● The data created by the user and assigned to
variables with an assignment statement is
sufficient for some applications.
● With large volume of data most real-world
applications use a better way of storing that
data.
● For this, disk files offer the solution.
● When working with disk files, C++ does not
have to access much RAM because C++ reads
data from your disk drive and processes the
data only parts at a time.
Chapter 4: File Management 3
Stream hierarchy
ios

istream ostream

ifstream iostream ofstream

fstream
Chapter 4: File Management 4
Stream hierarchy cont’d
● According to the above hierarchy, the class iostream is derived
from the two classes’ istream and ostream and both istream
and ostream are derived from ios.
● Similarly the class fstream is derived from iostream.
● Generally two main header files are used iostream and
fstream.
● The classes used for input from keyboard and output to the
video display are declared in the header file iostream while the
classes used for disk file input/output are declared in fstream.
● Note that when we include the header file fstream in our
program then there is no need to include iostream header file
as all the classes in fstream are derived from those in iostream
therefore, we can use all the functions of iostream class.

Chapter 4: File Management 5


Types of Disk File Access
● Your program can access files either in sequential
manner or random manner.
● The access mode of a file determines how one can read,
write, change, add and delete data from a file.
● A sequential file has to be accessed in the same order as
the file was written.
● This is analogues to cassette tapes: you play music in the
same order as it was recorded.
● Unlike the sequential files, you can have random-access
to files in any order you want.
● Think of data in a random-access file as being similar to
songs on compact disc (CD): you can go directly to any
song you want to play without having to play or fast-
forward through the other songs.
Chapter 4: File Management 6
What File IO?
● You are already using files to store your programs. You can also use
files to store input for a program or to receive output from a program.
● The files used for program I/O are the same kind of files you use to
store your programs.
● Streams, which we discuss next, allow you to write programs that
handle file input and keyboard input in a unified way and that handle
file output and screen output in a unified way.
● A stream is a flow of characters (or other kind of data).
○ If the flow is into your program, the stream is called an input stream.

○ If the flow is out of your program, the stream is called an output stream.
● If the input stream flows from the keyboard, then your program will
take input from the keyboard. If the input stream flows from a file, then
your program will take its input from that file.
● Similarly, an output stream can go to the screen or to a file.

Chapter 4: File Management 7


What is stream?
● In C++, a stream is a special kind of variable known as an object. It is a
general name given to flow of data
● You have already been using streams in your programs. The cin that
you have already used is an input stream connected to the keyboard,
and cout is an output stream connected to the screen.
● These two streams are automatically available to your program, as
long as it has an include directive that names the header file
iostream.
● You can define other streams that come from or go to files; once you
have defined them, you can use them in your program in the same
way you use the streams cin and cout.
● For example, suppose your program defines a stream called inStream
that comes from some file. You can then fill an int variable named
num with a number from this file by using the following in your
program:
int num;

inStream >> num; Chapter 4: File Management 8


What is stream cont’d
● Similarly, if your program defines an output stream named outStream
● that goes to another file, then you can output the value of this variable
to this other file.
● The following will output the string “num is" followed by the contents
of the variable num to the output file that is connected tot he stream
outStream:
outStream << “num is" << num<< endl;
● Once the streams are connected to the desired files, your program can
do file I/O the same way it does I/O using the keyboard and screen.
● You can think of the file that a stream is connected to as the value of
the stream.
● You can disconnect a stream from one file and connect it to another
file, so you can change the value of these stream variables
● Note that streams are unusual sorts of variables thus you cannot use
a stream variable in an assignment statement the way use a variable
of type int or char.
Chapter 4: File Management 9
Why use files for io?
● The keyboard input and screen output we have used so far deal with
temporary data.
● When the program ends, the data typed in at the keyboard and the
data left on the screen go away. Files provide you with a way to store
data permanently.
● The contents of a file remain until a person or program changes the
file.
● If your program sends its output to a file, the output file will remain
after the program has finished running.
● An input file can be used over and over again by many programs
without the need to type in the data separately for each program.
● The input and output files used by your program are the same kind
of files that you read and write with an editor, such as the editor you
use to write your programs.
● This means you can create an input file for your program or read an
output file produced by your program whenever it’s convenient for
you, as opposed to having to do all your reading and writing while
the program is running.
Chapter 4: File Management 10
Declaring a stream
● The streams cin and cout are already declared for you,
but if you want a stream to connect to a file, you must
declare it just as you would declare any other variable.
● The type for input-file stream variables is named
ifstream (for“ input-file stream”). The type for output-
file stream variables is named ofstream (for “output-
file stream”).
● You can declare inStream to be an input stream for a
file and outStream to be an output stream for another
file as follows:
ifstream inStream;

ofstream outStream;
Chapter 4: File Management 11
Declaring a stream cont’d
● The types ifstream and ofstream are defined in the
library with the header file fstream, and so any program
that declares stream variables in this way must contain
the following directive (normally near the beginning of
the file):
#include <fstream>
● When using the types ifstream and ofstream, your
program must also contain the following, normally either
at the start of the file or at the start of the function body
that uses the types ifstream or ofstream:
using namespace std;

Chapter 4: File Management 12


Connecting a stream to a file…
● Stream variables, such as inStream and outStream
declared earlier, must each be connected to a file. This
is called opening the file and is done with a function
named open. For example, suppose you want the input
stream
● inStream connected to the file named infile.dat. Your
program must then contain the following before it reads
any input from this file:
inStream.open("infile.dat");
● You can also combine file opening with the declaration of
the stream variable as follows:
ifstream inStream("infile.dat"); //constructor method,
● Here, an object named inStream of ifstream class is
created and this object is associated with file name
“infile.dat”
Chapter 4: File Management 13
Reading and writing

● Once you have declared an input stream variable and


connected it to a file using the open function or using a
constructor method, your program can take input from the file
using the extraction operator >>. For example, the following
reads two input numbers from the file connected to inStream
and places them in the variables num1and num2:
int num1, num2;
inStream >> num1>> num2;
● An output stream is opened (that is, connected to a file) in the
same way as just described for input streams. For example, the
following declares the output stream outStream and connects it
to the file named outfile.dat:
ofstream outStream;
outStream.open("outfile.dat");
Chapter 4: File Management 14
Reading and writing cont’d
● When used with a stream of type ofstream, the member
function open will create the output file if it does not
already exist. If the output file does already exist, the
member function open will discard the contents of the
file so that the output file is empty after the call to open.
● After a file is connected to the stream outStream with a
call to open, the program can send output to that file
using the insertion operator <<.
● The following writes two strings and the contents of the
variables num1 and num2 to the file that is connected to
the stream outStream (which in this example is the file
named outfile.dat):
outStream << “num1= " << num1
<< " num2= " << num2;
Chapter 4: File Management 15
File access mode
● Access mode is the sought operation to be
taken on the file.

Mode Description
app Opens file for appending

ate Seeks to the end of file while opening the file

in Opens the file for reading

out Opens the file for writing

binary Opens the file in binary mode

Chapter 4: File Management 16


File access mode cont’d
● If a file is opened for writing (with access mode out), C++
creates the file automatically
○ If a file by that name already exists, C++ overwrite the old file with
no warning.
○ You must be careful when opening files not to overwrite existing
data that you want.
● If an error occurs during opening of a file, C++ does not
create a valid file pointer (file object).
● Instead, C++ creates a file pointer (object) equal to zero. For
example if you open a file for output, but use an invalid
disk name, C++ can’t open the file and therefore makes the
file object equal to zero.
● Syntax to open a file with open function:
fileobject.open(filename,accessmode);

Chapter 4: File Management 17


File access mode cont’d
● You should always check for the successful opening
of a file before starting file manipulation on it.
● You use the fail() function to do the task:
ifstream indata;
indata.open(“c:\\myfile.txt”,ios::in);
if(indata.fail()) {
//error description here
exit(1);
}
● In this case, the open operation will fail (i.e
the fail function will return true), for instance
if there is no file to read from, named
myfile.txt in the directory C:\
Chapter 4: File Management 18
Chapter 4: File Management 19
Disconnect a stream from a file
● You can perform three operations on sequential disk files.
You can create disk files, add to disk files, and read from
disk files.
● When you open a disk file, you only have to inform C++,
the file name and what you want to do with it.
● C++ and your operating system work together to make
sure that the disk is ready, and they create an entry in your
file directory for the filename (if you are creating a file).
● Once you are done with these file operations, you need to
disconnect the stream from the file- close the file
● When you close a file, C++ writes any remaining data to
the file, releases the file from the program, and updates
the file directory to reflect the file’s new size.
Chapter 4: File Management 20
Disconnect a stream from a file cont’d
● After you are done with your file
manipulations, you should use the close
function to release any resources that were
consumed by the file operation. Here is an
example

indata.close();
● The above close() statement will terminate
the relationship between the ifstream object
indata and the file name “c:\myfile.txt”, hence
releasing any resource needed by the system.
Chapter 4: File Management 21
Character IO
● All data is input and output as character data. When your program
outputs the number 10, it is really the two characters '1' and '0' that are
output.
● Similarly, when the user wants to type in the number 10, he or she types
in the character '1' followed by the character '0'. Whether the computer
interprets this 10 as two characters or as the number 10 depends on how
your program is written. But, however your program is written, the
computer hardware is always reading the characters '1' and '0', not the
number 10.
● This conversion between characters and numbers is usually done
automatically so that you need not think about such detail.
● Therefore, C++ provides some low-level facilities for input and output of
character data. These low-level facilities include no automatic conversions.
This allows you to bypass the automatic facilities and do input/output in
absolutely any way you want. You could even write input and output
functions that read and write numbers in Roman numeral notation
Chapter 4: File Management 22
Member functions get and put
● The function get allows your program to read in one character
of input and store it in a variable of type char.
● Every input stream, whether it is an input file stream or the
stream cin, has get as a member function.
● get as a member function of the stream cin, behaves in exactly
the same way for input file streams
● Before now, we have used cin with the extraction operator >>
in order to read a character of input (or any other input, for
that matter). When you use the extraction operator >>, as we
have been doing, some things are done for you automatically,
such as skipping blanks.
● With the member function get, nothing is done automatically. If
you want, for example, to skip over blanks using cin.get, you
must write code to read and discard the blanks.
Chapter 4: File Management 23
Member functions get and put cont’d
● The member function get takes one argument, which should be a variable of
type char. That argument receives the input character that is read from the
input stream (connected to the keyboard or to a file). For example, the
following reads in the next input character from the keyboard and stores it in
the variable nextChar:
char nextChar;
cin.get(nextChar);
● It is important to note that your program can read any character in this way.
If the next input character is a blank, this code will not skip over the blank,
but will read the blank and set the value of nextChar equal to the blank
character.
● If the next character is the new-line character '\n', that is, if the program has
just reached the end of an input line,
andthen
supposethe call
you to cin.get
type in theshown earlier
following two
sets the value of nextChar equal tolines
'\n'.of input to be read by this code:
For example, suppose your program
contains the following code: AB
char c1, c2, c3; CD
cin.get(c1); What will cout<<c3 display?//C? No! Why not? What if
you use cin>>c1>>c2>>c3; and entered the same input
cin.get(c2); from the keyboard? Explain.
cin.get(c3);

Chapter 4: File Management 24


Predefined functions for reading and writing
● and write to a file reading from a file
● The most common file I/O functions are
get() and put()
○ get() to read from a file and
○ put() to write to a file
● get() and put() are used with dot operator
(example next slide) for writing to a file via
put()

Chapter 4: File Management 25


Writing characters to a
sequential file
#include<fstream>
#include<stdlib>// for exit() function

void main()
{
char c;
ofstream outfile;
outfile.open(“c:\\
test.txt”,ios::out); for(int i=1;i<=15;i++)
{
if(outfile.fail()) { cout<< “\nEnter a character : ”;
cerr<< “\nError opening cin>>c;
test.txt”; outfile.put(c);
getch(); }
exit(1); outfile.close();
} }//end main

Chapter 4: File Management 26


Writing to a file
● You can also use the output redirection operator (<<) to write to a
file.
● The following program creates a file called names.txt in C:\ and
saves the name of five persons in it:
#include<fstream>
#include<stdlib>
using namespace std;
ofstream fp;
void main( ) {
fp.open(“c:\\names.txt” ,ios::out);
if(fp.fail()) {
cout<< “\nError opening file”;
exit(1); }
fp<< “Abebe Alemu”<<endl;
fp<< “Lemlem Berhanu”<<endl;
fp<< “Tesfaye Mulugeta”<<endl;
fp<< “Mahlet Kebede”<<endl;
fp<< “Assefa Bogale”<<endl;
fp.close();
Chapter 4: File Management 27
Writing to a file cont’d
● The program (previous slide) reads 15
characters and stores the characters in file
test.txt.
● You can easily add data to an existing file, or
create new files, by opening the file in
append access mode (ios::app).
● Files you open for append access mode
(using ios::app) do not have to exist, if it does
not exist, C++ creates it; If the file exists, C++
appends data to the end of the file (as is
done when you open a file for write access).
Chapter 4: File Management 28
● The program adds three more names to the names.txt file created in the earlier program.
#include<fstream>
#include<stdlib>//for exit(1)
#include<conio.h>//for getch()

void main()
{
ofstream outdata;
outdata.open(“c:\\names.txt”,ios::app);
if(outdata.fail()){
cout<< “\nError opening names.txt”;
getch();//defined in header file <conio.h>
exit(1);
}
outdata<< “Berhanu Teka”<<endl;
outdata<< “Zelalem Assefa”<<endl;
outdata<< “Dagim Sheferaw”<<endl;
outdata.close();
}//end main
Chapter 4: File Management 29
Reading from a File
● Files you open for read access (using ios::in) must
exist already, or C++ gives you an error message. You
can’t read a file that does not exist. Open() returns
zero if the file does not exist when you open it for
read access.
● Another event happens when you read files.
Eventually, you read all the data. Subsequently
reading produces error because there is no more
data to read. C++ provides a solution to the end-of-
file occurrence.
● If you attempt to read a file that you have completely
read the data from, C++ returns the value zero. To
find the end-of-file condition,
Chapter 4: File Management be sure to check for 30
File position pointers
● Programs normally read sequentially from the beginning of a file and read all
the data consecutively until the desired data is found
● It might be necessary to process the file sequentially several times (from the
beginning) during the execution of a program.
● istream and ostream provide member functions—seekg (“seek get”) and seekp
(“seek put”), respectively—to reposition the file-position pointer (the byte
number of the next byte in the file to be read or written).
● Each istream object has a get pointer, which indicates the byte number in the file
from which the next input is to occur, and each ostream object has a put pointer,
which indicates the byte number in the file at which the next output should be
placed.
● The statement inFile.seekg(0); repositions the file-position pointer to the
beginning of the file (location 0) attached to inFile object.
● The argument to seekg is an integer. A second argument can be specified to
indicate the seek direction, which can be ios::beg (the default) for positioning
relative to the beginning of a stream, ios::cur for positioning relative to the
current position in a stream or ios::end for positioning backward relative to the
end of a stream.

Chapter 4: File Management 31


File position pointers cont’d
● The file-position pointer is an integer value that specifies the location in
the file as a number of bytes from the file’s starting location (this is also
referred to as the offset from the beginning of the file).
● Some examples of positioning the get file-position pointer are
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg(n);
// position n bytes in fileObject
fileObject.seekg(n, ios::cur);
// position n bytes back from end of fileObject
fileObject.seekg(n, ios::end);
// position at end of fileObject
fileObject.seekg(0, ios::end);
● The same operations can be performed using ostream member
function seekp.
● Member functions tellg and tellp are provided to return the current
locations of the get and put pointers, respectively.
● The following statement assigns the get file-position pointer value to
variable location of type long:
location = fileObject.tellg();

Chapter 4: File Management 32


● The following code asks the user for a file
name and displays the content of the file
to the screen.
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
void main(){
// clrscr(); clrscr() is not a standard C++
while(!indata.eof())//
function checks for the end-of-
char name[20],filename[15]; file
ifstream indata; {
cout<<"\nEnter the file name : ";
cin.getline(filename,15);
indata>>name;
indata.open(filename,ios::in);
if(indata.fail()) { cout<<name<<endl;
cerr<<"\nError opening file : }
"<<filename; indata.close();
getch();
exit(1);
getch();
} }

Chapter 4: File Management 33


Reading characters from a sequential file
● You can read a characters from a file using
get() function. The following program asks for
a file name and displays each character of the
file to the screen.

Chapter 4: File Management 34


indata.open(filename,ios::in);
if(indata.fail())// check if it opens
#include<fstream.h> {
#include<stdlib.h> cerr<<"\nError opening file :
void main() "<<filename;
{ exit(1);
char c,filename[15]; }
ifstream indata; while(!indata.eof())// check for
cout<<"\nEnter file eof
name : "; {
cin.getline(filename,15); indata.get(c);
cout<<c;
}
indata.close();

}
Chapter 4: File Management 35
File Pointer and their Manipulators
● Each file has two pointers one is called input pointer and second is
output pointer.
● The input pointer is called get pointer and the output pointer is called
put pointer.
● When input and output operation take places, the appropriate pointer
is automatically set according to the access mode.
● For example when we open a file in reading mode, file pointer is
automatically set to the start of the file.
● When we open a file in append mode, the file pointer is automatically
set to the end of file.
● In C++ there are some manipulators by which we can control the
movement of the pointer. The available manipulators are:
seekg()
seekp()
tellg()
tellp()
Chapter 4: File Management 36
● seekg(): this moves get pointer i.e input pointer to a
specified location.
eg. infile.seekg(5);
● seekp(): this move put pointer (output pointer) to a
specified location for example: outfile.seekp(5);
● tellg(): this gives the current position of get pointer
(input pointer)
● tellp(): this gives the current position of put pointer
(output pointer)
eg. ofstream fileout;
fileout.open(“c:\\test.txt”,ios::app);
int length = fileout.tellp();
● By the above statement in length, the total number
bytes of the file are assigned to the integer variable
length. Because the file is opened in append mode
that means, the file pointer is the last part of the file.
Chapter 4: File Management 37
Now lets see the seekg() function in
action
#include<fstream.h>
#include<conio.h>
#include<stdlib.h> //now write the characters to the file
void main() for(ch = 'A'; ch <= 'Z'; ch++)
{
{
fileobj<<ch;
//clrscr(); }
fstream fileobj; fileobj.seekg(8L,ios::beg);//skips eight
char ch; //holds A through Z letters, points to I
fileobj.open("c:\\alph.txt“); fileobj>>ch;
if(fileobj.fail()) cout<<"\nThe 8th character is : "<<ch;
{ fileobj.seekg(16L,ios::beg);//skips 16
letters, points to Q
cerr<<"\nError opening alph.txt";
fileobj>>ch;
getch(); cout<<"\nThe 16th letter is : "<<ch;
exit(1); fileobj.close();
} getch();
}

Chapter 4: File Management 38


● To point to the end of a data file, you can use the seekg()
function to position the file pointer at the last byte. This
statement positions the file pointer to the last byte in the file.
Fileobj.seekg(0L,ios::end);
● This seekg() function literally reads “move the file pointer 0
bytes from the end of the file.” The file pointer now points to
the end-of-file marker, but you can seekg() backwards to find
other data in the file.
● The following program is supposed to read “c:\alph.txt” file
backwards, printing each character as it skips back in the file.
● Be sure that the seekg() in the program seeks two bytes
backwards from the current position, not from the beginning
or the end as the previous programs. The for loop towards
the end of the program needs to perform a “skip-two-bytes-
back”, read-one-byte-forward” method to skip through the
file backwards.
Chapter 4: File Management 39
#include<fstream.h>
#include<conio.h> indata.seekg(-1L,ios::end);//
#include<stdlib.h>
points to the last byte in the file
void main()
{ for(ctr=0;ctr<26;ctr++)
clrscr();
{
ifstream indata;
int ctr=0; indata>>inchar;
char inchar;
indata.seekg(-2L,ios::cur);
indata.open("c:\\alph.txt",ios::in); cout<<inchar;
if(indata.fail())
{
}
cerr<<"\nError opening alph.txt"; indata.close();
getch();
exit(1);
getch();
} }

Chapter 4: File Management 40


Text Files And Binary Files (Comparison)
● The default access mode for file access is text mode.
● A text file is an ASCII file, compatible with most other programming
languages and applications.
● Programs that read ASCII files can read data you create as C++ text
files.
● If you specify binary access, C++ creates or reads the file in binary
format. Binary data files are “squeezed”- that is, they take less space
than text files.
● The disadvantage of using binary files is that other programs can’t
always read the data files.
● Only C++ programs written to access binary files can read and write
them. The advantage of binary files is that you save disk space
because your data files are more compact.
● The binary format is a system-specific file format.
● In other words, not all computers can read a binary file created on
another computer.
Chapter 4: File Management 41
End!

Chapter 4: File Management 42

You might also like