0% found this document useful (0 votes)
14 views29 pages

CP Chapter 7

This document discusses file handling in C++. It covers: 1) The basics of file management, including logical and physical files, file variables, and C++ file I/O classes. 2) Streams and files, including text and binary streams, and how streams provide abstraction between programs and devices. 3) Opening, writing, reading, and closing files using fstream objects and flags like ios::in and ios::out. 4) Examples of writing to a file by appending, reading specific words from a file, and reading the entire contents of a file. 5) Error handling when opening files and random access of files using seekg() and seekp()

Uploaded by

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

CP Chapter 7

This document discusses file handling in C++. It covers: 1) The basics of file management, including logical and physical files, file variables, and C++ file I/O classes. 2) Streams and files, including text and binary streams, and how streams provide abstraction between programs and devices. 3) Opening, writing, reading, and closing files using fstream objects and flags like ios::in and ios::out. 4) Examples of writing to a file by appending, reading specific words from a file, and reading the entire contents of a file. 5) Error handling when opening files and random access of files using seekg() and seekp()

Uploaded by

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

Chapter 7

Working with Files


1
2 File Management
 File handling is an important part of all programs. Most
of the applications will have their own features to save
some data to the local disk and read data from the disk
again.
 Files which are on the secondary storage device are
called physical files. In order to process file through
program, logical file must be created on the RAM.
 This logical file is nothing but an object having file data
type. As an object there should be a variable identifier
that points to it. This variable is called file variable and
some times also called file handler.
 C++ File I/O classes simplify such file read/write
operations for the programmer by providing easier to
use classes.
3 Streams and Files
 The I/O system supplies a consistent interface to the C++
programmer independent of the actual device being
accessed. This provides a level of abstraction between the
programmer and the device. This abstraction is called
stream. The actual device is called a file.
 Streams
 The C++ file system is designed to work with a wide variety
of devices, including terminals, disk drives, and tape drives.
 Even though each device is very different, the C++ file
system transforms each into a logical device called stream.
There are two types of streams: text and binary.
4 Cont..
1. Text Streams
 A text stream is a sequence of characters. In a text stream,
certain character translations may occur as required by the
host environment. For example a new line may be
converted to a carriage return/linefeed pair.
 There may not be a one-to-one relationship between the
characters that are written (or read) and those on the
external device. Because of possible transformations, the
number of characters written (or read) may not be the same
as those on the external device.
 Text file is a file in which its content is treated as a
sequence of characters and can be accessed sequentially.
5 Cont..
2. Binary streams
 A binary stream is a sequence of bytes with a one-to-
one correspondence to those in the external device
i.e., no character translations occur.
 The number of bytes written (or read) is the same as
the number on the external device. However, an
implementation-defined number of null bytes may be
appended to a binary stream. These null bytes might
be used to pad the information so that it fills a sector
on a disk.
 binary file is a file in which its content is treated as
record sequence in a binary format.
6 C++ files and Streams
 So far, we have been using the iostream standard
library, which provides cin and cout methods for
reading from standard input and writing to standard
output respectively.
 In this chapter, we will see how to read and write from
a file. This requires another standard C++ library called
fstream, which defines three new data types:
 ofstream – An output file stream which is used to
create files and to write information to files.
 ifstream – An input file stream which is used to read
information from files.
 fstream -Has the capabilities of both ofstream and
ifstream which means it can create files, write
information to files, and read information from files.
7 Using a File
 Using a file in a program is a simple three-steps process
 The file must be opened. If the file does not yet
exist, opening it means creating it.
 Information is then saved to the file, read from the
file, or both.
 When the program is finished using the file, the file
must be closed.
8 Opening a File
 A file must be opened before you can read from it or
write to it. Either the ofstream or fstream object may
be used to open a file for writing and ifstream object
is used to open a file for reading purpose only.
 In order to open a file with a stream object we use its
member function open:
open (filename, mode);
 Where filename is a string representing the name of
the file to be opened, and mode is an optional
parameter with a combination of the following flags:
9 File Opening Modes (Flags)
Mode Flag Description
Append mode. All output to that file to be
ios::app
appended to the end.
Open a file for output and move the read/write
ios::ate
control to the end of the file.
ios::in Open a file for reading.
ios::out Open a file for writing.
If the file already exists, its contents will be
ios::trunc
truncated before opening the file.

 All these flags can be combined using the bitwise


operator OR (|).
10 Cont..

 For example if you want to open a file in write mode


and want to append data into it, following will be the
syntax:
ofstream outfile;
outfile.open(“myfile.txt", ios::out | ios::app );
 Similarly, you can open a file for reading and writing
purpose as follows:
fstream afile;
afile.open("file2.dat", ios::out | ios::in );
11 Writing to a file … Example
#include<iostream.h>
xyz.txt
#include<conio.h>
#include<fstream.h> This is my message to you
int main() Stay Hungry ... Stay Foolish
{
fstream outfile;
Says Steve Jobs
outfile.open("xyz.txt",ios::out);
cout<<"Writing to a file";
outfile<<"\nThis is my message to you\n";
outfile<<"Stay Hungry ... Stay Foolish \n";
outfile<<"Says Steve Jobs";
cout<<"\nDone.";
outfile.close();
getch();
return 0;
}
Writing to a file(appending) …
12 Example
#include<iostream.h>
#include<conio.h> xyz.txt
#include<fstream.h> This is my message to you
int main()
{
Stay Hungry ... Stay
fstream outfile; Foolish
outfile.open("xyz.txt",ios::out|ios::app); Says Steve Jobs
cout<<"Writing to an existing file by
appending"; Here is another message
outfile<<"\n Here is another message\n"; I would rather program
outfile<<“I would rather program than
play TicTacToe\n";
than play TicTacToe
outfile<<"Says Bill Gates"; Says Bill Gates
cout<<"\nDone.";
outfile.close();
getch();
return 0;
}
Reading from a file… Example
13
#include<iostream.h>
#include<conio.h> Output Window
#include<fstream.h> This is my message
int main()
{
//Reading from a file
char msg[20];
fstream infile;
infile.open("xyz.txt",ios::in);
for(int w=1;w<=4;w++) //Read only 4 words
{ infile>>msg;
cout<<msg<<" ";
}
infile.close();
getch();
return 0;
}
14 Reading all contents of a file …
Example
#include<iostream.h>
Output Window
#include<fstream.h>
int main() This is my message to you
{ Stay Hungry ... Stay
//Reading from a file
char msg[70];
Foolish
fstream infile; Says Steve Jobs
infile.open("xyz.txt",ios::in);
Here is another message
while(!infile.eof()) //Read until the end of the file
{ I would rather program
infile.getline(msg,70); //Read a line than play TicTacToe
cout<<msg<<"\n";
}
Says Bill Gates
infile.close();
return 0;
}
15 File Open Error … Example
#include<iostream.h>
Output Window
#include<fstream.h>
int main() Error Opening file
{
char msg[70];
ifstream infile;
infile.open("x.txt",ios::in); //Assume x.txt
doesn’t exist
if(infile.fail())
cout<<"Error Opening file";
else
{
infile>>msg;
infile.close();
}
return 0;
}
16 Random Access Files

 Random Access means non-sequentially


accessing information in a file.
 It use seekg() and seekp(); function to access.
17 seekg() and seekp()
 These functions allow us to change the position of the
get and put stream pointers. Both functions are
overloaded with two different prototypes.
 The prototype it use:
 seekg ( offset, mode);
 seekp ( offset, mode);
 Using this prototype, the position of the get or put
pointer is set to an offset value relative to some
specific point determined by the parameter
direction(mode)
18 Modes to random access
Mode Flag Description

ios::b eg The offset is calculated from


the beginning of the file.
ios::en d The offset is calculated from
the end of the file.
ios::cu r The offset is calculated from
the current position.
Examples for setting random access
19
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, ios::end); Sets the read position to the 101st byte (byte 100)
from 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.
20 Seekg()… Example
#include<iostream.h>
Assume “xy.txt” has:
#include<fstream.h>
int main() 123456789
{
fstream f("xy.txt",ios::in|ios::out);
char m[100];int x,y;char c;
for(int i=0;i<10;i+=2)
{
Output Window
f.seekg(i,ios::beg); 13579
f>>c;
cout<<c<<“ “;
}
return 0;
}
21 Seekp() … Example
#include<iostream.h> Assume “xy.txt” has:
#include<fstream.h> hello
int main()
Previously before seekp()
{
fstream f("xy.txt",ios::in|ios::out);
f.seekp(3,ios::beg);
f<<"A"; After seekp()“xy.txt” changed:
return 0;
helAo
}
22 tellg() and tellp()
 These two member functions have no parameters
and return a value of the member type pos_type,
which is an integer data type representing the
current position of the get stream pointer (in the
case of tellg) or the put stream pointer (in the
case of tellp).
23 Example
#include <iostream>
#include <fstream> Assume “example.txt” has:
using namespace std; this is tellg
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg(); Output Window
cout<<"before seekg = "<<begin<<endl;
myfile.seekg (0, ios::end);
before seekg = 0
end = myfile.tellg(); after seekg = 13
cout<<"after seekg = "<<end<<endl; size is: 13 bytes.
myfile.close();
cout << "size is: " << (end-begin) << "
bytes.\n";
return 0;
}
24 Binary File processing
 There are two ways to write and read binary data to
and from a file.
 get ( ) and put ( )
 read ( ) and write ( )
 If you will be performing binary operations on a file,
be sure to open it using the ios::binary mode
specifier.
25 get ( ) and put ( )
 These functions are byte-oriented.
 get ( ) will read a byte of data.
 put ( ) will write a bye of data.
 The get ( ) method has many forms.
 istream & get( char & ch );
 ostream & put ( char ch);
 The get ( ) method read a single character from the
associated stream and puts the value in ch, and
returns a reference to the stream.
 The put ( ) method writes ch to the stream and
returns a reference to the stream.
Writing in the binary file
26
#include<iostream.h> Input Window
#include<fstream.h>
int main()
Enter a character : h
{ Enter a character : e
char c; Enter a character : l
ofstream outfile;
Enter a character : l
outfile.open("test.txt",ios::out:ios::binary);
if(outfile.fail())
Enter a character : o
{ cerr<<"\nError opening test.txt";
exit(1); }
test.txt
for(int i=1;i<=5;i++)
{ cout<<"\nEnter a character : "; hello
cin>>c;
outfile.put(c);}
outfile.close();
return 0; }
27 Reading from binary file
#include<iostream.h>
Assume “test.txt” has:
#include<fstream.h>
int main()
Software first year
{ char c;
ifstream infile;
infile.open("test.txt",ios::in|ios::binary);
if(infile.fail())
{ cerr<<"\nError opening test.txt"; Output Window
exit(1); } Software first year
while(!infile.eof()){
infile.get(c);
cout<<c; }
infile.close();
return 0;
}
28 Reading Assignment
 read ( ) and write ( ) binary file
processing
29 Exercise
1. Write a program that writes into a file (say
“even.txt”) the first 20 even numbers.
2. Modify the above program so that it can read the
first 10 even numbers from the file “even.txt”.
3. Modify the above program so that it can append a
message “The above are even numbers” at the end
of the file “even.txt”.

You might also like