0% found this document useful (0 votes)
8 views50 pages

Chapter 3 File Operations

Chapter Three covers file operations in C++, focusing on file-based input and output, including the creation and manipulation of sequential and random access files. It explains the concept of streams, how to connect them to files, and the various file access modes available. Additionally, it emphasizes the importance of handling file I/O errors and the distinction between text and binary files.

Uploaded by

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

Chapter 3 File Operations

Chapter Three covers file operations in C++, focusing on file-based input and output, including the creation and manipulation of sequential and random access files. It explains the concept of streams, how to connect them to files, and the various file access modes available. Additionally, it emphasizes the importance of handling file I/O errors and the distinction between text and binary files.

Uploaded by

abelalex530
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter Three

File Operations (File I/O)

1
Objectives

● At the end of this chapter students will be able to


● Identify the need for file based input and output
● Identify files and streams
● Create sequential files in C++
● Identify file access modes in C++
● Read data from and write to a sequential file
● Create a random access file
● Read from and write to a random access file
● Identify and handle file I/O errors
● Differentiate text files from binary files

Chapter 3: File Operations (File I/O) 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 3: File Operations (File I/O) 3
Introduction
● C++ views each file simply as a sequence of
bytes (see figure).
● Each file ends either with an end-of-file marker
or at a specific byte number recorded in an os
maintained administrative data structure
● When a file is opened, an object is created, and
a stream is associated with the object

Chapter 3: File Operations (File I/O) 4


Introduction
● Recall that objects cin, cout, cerr and clog are created when
<iostream> is included
● The streams associated with these objects provide communication
channels between a program and a particular file or device
● For example,

○ the cin object (standard input stream object) enables a program


to input data from the keyboard or from other devices,

○ the cout object (standard output stream object) enables a


program to output data to the screen or other devices, and

○ the cerr and clog objects (standard error stream objects)


enable a program to output error messages to the screen or
other devices

Chapter 3: File Operations (File I/O) 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 3: File Operations (File I/O) 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 3: File Operations (File I/O) 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, along with the using namespace std; statement
● 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 3: File Operations (File I/O) 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 to the 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 3: File Operations (File I/O) 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 3: File Operations (File I/O)
1
0
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
object for a file and outStream to be an output
stream object for another file as follows:
ifstream inStream;
ofstream outStream;
Chapter 3: File Operations (File I/O)
1
1
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 3: File Operations (File I/O)


1
2
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 infi[Link].
Your program must then contain the following before it
reads any input from this file:
[Link]("infi[Link]");
● You can also combine file opening with the declaration of
the stream variable as follows:
ifstream inStream("infi[Link]"); //constructor method,
● Here, an object named inStream of ifstream class is
created and this object is associated with file name
“infi[Link]”

Chapter 3: File Operations (File I/O)


1
3
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 outfi[Link]:
ofstream outStream;
[Link]("outfi[Link]");

Chapter 3: File Operations (File I/O)


1
4
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 outfi[Link]):
outStream << “num1= " << num1
<< " num2= " << num2; 1
Chapter 3: File Operations (File I/O)
5
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 3: File Operations (File I/O)
1
6
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 by accident
● 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 or
null
● 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:
fi[Link](filename,accessmode);
Chapter 3: File Operations (File I/O)
1
7
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;
[Link](“c:\\myfi[Link]”,ios::in);
if([Link]()) {
//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 myfi[Link] in the directory C:\

Chapter 3: File Operations (File I/O)


1
8
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 deal with
● 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, i.e, 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 3: File Operations (File I/O)


1
9
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
[Link]();
● The above close() statement will terminate the
relationship between the ifstream object
indata and the file name “c:\\myfi[Link]”,
hence releasing any resource needed by the
system.
Chapter 3: File Operations (File I/O)
2
0
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 you want to type in the number 10, you key 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
Low-level I/O in C++ lets you read/write raw character or byte data without automatic

type conversions, giving you direct control over the data.

Chapter 3: File Operations (File I/O)


2
1
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 [Link],
you must write code to read and discard the blanks
Chapter 3: File Operations (File I/O)
2
2
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;
[Link](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, then the call to [Link] shown earlier
sets the value of nextChar equal to '\n'.
For example, suppose your program and suppose you type in the following two
contains the following code: lines of input to be read by this code:
char char1, char2, char3; AB CD
What will cout<<char3 display?//C? No! Why not? What if
[Link](char1); you use cin>>char1>>char2>>char3; and entered the
[Link](char2); same input from the keyboard? Explain.
[Link](char3); 2
Chapter 3: File Operations (File I/O)
3
Takeaway exercise: compare cin>> and [Link]

Chapter 3: File Operations (File I/O)


2
4
Predefined functions for reading and writing
● 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 the dot
operator (example next slide) for writing
to a file via put()

Chapter 3: File Operations (File I/O)


2
5
Writing characters to a
sequential file
#include<iostream>
#include<fstream>
#include<cstdlib>// for exit() function

int main()
{
char c;
ofstream outfile;
outfi[Link](“[Link]”,ios::out); for(int i=1;i<=15;i++)
{
if(outfi[Link]()) { cout<< “\nEnter a character : ”;
cerr<< “\nError opening cin>>c;
[Link]”; [Link](c);
exit(1); }
} [Link]();
return 0;
}
Chapter 3: File Operations (File I/O)
2
6
Writing to a file
● You can also use the output redirection operator or the insertion operator
(<<) to write to a file
● The following program creates a file called [Link] in C:\ and saves the
name of five persons in it:
#include<fstream>
#include<stdlib>
using namespace std;
ofstream fp;
int main( ) {
[Link](“c:\\[Link]” ,ios::out);
if([Link]()) {
cout<< “\nError opening file”;
exit(1); }
fp<< “Eden Girma”<<endl;
fp<< “Feven Berhanu”<<endl;
fp<< “Solomon Dawit”<<endl;
fp<< “Mahlet Tsega”<<endl;
fp<< “Selam Alem”<<endl;
[Link]();
return 0;
} Chapter 3: File Operations (File I/O)
2
7
Writing to a file cont’d
● The program (previous slide) sends the names
as a series of characters and stores the
characters in file [Link]
● 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 3: File Operations (File I/O)
2
8
● The program adds three more names to the [Link] file created in the earlier
program.
#include<iostream>
#include<fstream>
#include<cstdlib>//for exit(1)
int main() {
ofstream outdata;
[Link](“[Link]”,ios::app);
if([Link]()){
cout<< “\nError opening [Link]”;
exit(1); }
outdata<< “Berhanu Teka”<<endl;
outdata<< “Zelalem Assefa”<<endl;
outdata<< “Dagim Sheferaw”<<endl;
[Link]();
return 0; }

Chapter 3: File Operations (File I/O)


2
9
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, be sure to check for zero when
reading information from files

Chapter 3: File Operations (File I/O)


3
0
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 [Link](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. ios::beg → points at the first character

ios::end → points after the last character


Chapter 3: File Operations (File I/O)
3
1
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).
A file-position pointer is just a number..............

● Some examples of positioning the get file-position pointer are


// position to the nth byte of fileObject (assumes ios::beg)
fi[Link](n);
// position n bytes in fileObject
fi[Link](n, ios::cur);
// position n bytes back from end of fileObject
fi[Link](n, ios::end);
// position at end of fileObject
fi[Link](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.

Chapter 3: File Operations (File I/O)


3
2
Example: Examine what the following code does
● The following code asks the user for a file name and displays the
content of the file to the screen.
#include<iostream>
#include<fstream>
#include<cstdlib>
Using namespace std;
int main(){
char name[20],filename[15];
ifstream indata;
cout<<"\nEnter the file name : ";
[Link](filename,15);
[Link](filename,ios::in);
if([Link]()) { cout<<"\nError opening file : "<<filename;
exit(1); }
while(![Link]()){ //check for the end-of-file
indata>>name;
cout<<name<<endl;}
[Link]();
return 0;} 3
Chapter 3: File Operations (File I/O)
3
Reading characters from a sequential file
● You can read characters from a file using the

get() function
● The following program (next slide) asks for a

file name and displays each character of the


file to the screen

Chapter 3: File Operations (File I/O)


3
4
Example: Examine what the following code does
#include<iostream>
#include<fstream>
#include<cstdlib>
int main() {
char c,filename[15]; ifstream indata;
cout<<"\nEnter file name : ";
[Link](filename,15);
[Link](filename,ios::in);
if([Link]()) {// check to open
cerr<<"\nError opening file : "<<filename;
exit(1);
}
while(![Link]()) { // check eof
[Link](c);
cout<<c; }
[Link]();
return 0; }

Chapter 3: File Operations (File I/O)


3
5
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.
● get pointer and put pointer values specify the byte number in the
file where reading or writing will take place
● 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 3: File Operations (File I/O)


3
6
● seekg(): this moves get pointer i.e input pointer to a
specified location.
eg. infi[Link](5);
● seekp(): this move put pointer (output pointer) to a
specified location for example: outfi[Link](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;
fi[Link](“[Link]”,ios::app);
int length = fi[Link]();
● 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 3: File Operations (File I/O)
3
7
Manipulating File Pointers
● Remember that by default reading pointer and writing
pointer are set at the beginning and at the end (when
you open file in ios::app mode), respectively
● There are times when you must take control of the file
pointers yourself so that you can read from and
write to an arbitrary location in the file.
● This allows for random access to data with in
the file rather than sequential reading or writing
● The seekg() and tellg() functions allow you to set and
examine the get pointer.
● The seekp() and tellp() functions allow you to set and
examine the put pointer.

Chapter 3: File Operations (File I/O)


3
8
Manipulating File Pointers…
● With one argument :
fl.seekg(k);
fl.seekp(k);
where k is absolute position from the beginning. The
start of the file is byte 0
It will result in moving the pointer as shown-

File End
Begin

k bytes ^

File pointer

Chapter 3: File Operations (File I/O)


3
9
Function’s arguments

[Link](offset, refposition);

[Link](offset, refposition);

Number of bytes file Location from where File


pointer to be moved pointer is to be moved

Refposition takes one of the following forms :


•ios::beg Start of the file
•ios::cur current position of the pointer
•ios::end End of the file

Chapter 3: File Operations (File I/O)


4
0
seekg()
: function : (With two arguments )
Begin End
•[Link](m,ios::beg);
m bytes ^
Offset from Begin
Move to (mth byte in the file
Begin End
[Link](-m,ios::end);
^ m bytes
Offset from end
Go backward by m bytes from the end
Begin End
[Link](m,ios::cur);
m bytes ^
Offset from current
position
Go forward by m bytes from current pos
Chapter 3: File Operations (File I/O)
4
1
Example: seekg() in action : (With two arguments )
#include<iostream>
#include<fstream>
#include<cstdlib>

int main() {
fstream fileobj;//class for input and output operations
char ch; //holds A through Z
fi[Link]("[Link]“, ios::in | ios::out);
if(fi[Link]()) {
cout<<"\nError opening [Link]";
exit(1); }
//now write the characters to the file
for(ch = 'A'; ch <= 'Z'; ch++) {
fileobj<<ch; }
[Link](8L,ios::beg);//skips eight letters, points to I
fileobj>>ch;
cout<<"\nThe 8th character is : "<<ch;
[Link](16L,ios::beg);//skips 16 letters, points to Q
fileobj>>ch;
cout<<"\nThe 16th letter is : "<<ch;
[Link](); 4
Chapter 3: File Operations (File I/O)
return 0; } 2
● 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.
[Link](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 “[Link]” 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 3: File Operations (File I/O)


4
3
Example 2: seekg() in action : (With two arguments )
#include<fstream>
#include<conio>
#include<cstdlib>
int main() {
ifstream indata;
int index = 0;
char inchar;
[Link]("[Link]",ios::in);
if([Link]()) {
cout<<"\nError opening [Link]";
exit(1); }
[Link](-1L,ios::end);// a negative offset moves the pointer backward
for(index=0;index<26;ctr++) {
indata>>inchar;
[Link](-2L,ios::cur);
cout<<inchar; }
[Link]();
return 0; }

Chapter 3: File Operations (File I/O)


4
4
Regardinh seekg(-1L, ios::end) and seekg(-2L, ios::cur)
the last character in most cases......................

• Seekg(-1L, ios::end) moves the get pointer one byte


before the end of the file (if there are n bytes in the
file, this positions the pointer at the (n-1)th byte
• seekg(-2L, ios::cur) moves the get pointer two bytes
backward from its current position
• The ios::end reference point in seekg() points to the
position after the last byte in the file, the eof marker;
• thus, seekg(0, ios::end) positions the pointer at
the end of file and
• seekg(-1, ios::end)positions it at the last byte of
the data
• Takeaway question: trace and show the output of the
code in previous slide
Chapter 3: File Operations (File I/O)
4
5
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.
● A text file consists of readable characters
separated into lines by newline characters.
● (On most PCs, the newline character is
actually represented by the two-character
sequence of carriage return (ASCII 13), line
feed (ASCII 10). (\n)

Chapter 3: File Operations (File I/O)


4
6
Text Files and Binary Files
● If you specify binary access, C++ creates or reads the file in binary format.
● Binary data files are “squeezed”- ie, 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, meaning not all
computers can read a binary file created on another computer.
● A binary file stores data to disk in the same form in which it is represented in main
memory
● If you ever try to edit a binary file containing numbers you will see that the
numbers appear as nonsense characters.
● Not having to translate numbers into a readable form makes binary files somewhat
more efficient.
● Binary files also do not normally use anything to separate the data into lines.
● Such a file is just a stream of data with nothing in particular to separate
components.
Chapter 3: File Operations (File I/O)
4
7
Text Files Binary Files

● When using a text ● When using a


file, we write out binary file we write
separately each of whole record data to
the pieces of data the file at once.
about a given
record.
● but the numbers in
● The text file will be
the binary file will
readable by an
not be readable in
editor
this way.

Chapter 3: File Operations (File I/O)


4
8
Text Files Binary Files

● for the text file we will ● For the binary file we


use the usual output will use write to write to
operator(<<) and will the file,
output each of the pieces
of the record separately.
● with the text file we will
read each of the pieces of ● With the binary file we
record from the file will use the read
separately, using the function to read a
usual input operator(>>) whole record,
Takeaway question: compare and contrast text files and
binary files .
Chapter 3: File Operations (File I/O)
4
9
End of chapter 3

Chapter 3: File Operations (File I/O)


5
0

You might also like