You are on page 1of 18

Chapter 12 - Advanced File

Operations

From Starting Out With C++ by Tony


Gaddis

2004 Janna B. Gallaher


File Operations

InC++ there are three file stream defined


ifstream - Input file stream reads data from files to memory
ofstream - Output file stream creates files and writes data to
them
fstream - File stream creates files, writes data to them, and
reads data from them
File Operations (continued)
Using the fstream Data Type
fstream dataFile; creates an fstream object (e.g. fstream datafile;)
fstream objects can be opened for reading or writing with the following
switches:
ios::app = append mode adds data to the end of an existing file
ios::ate = adds data anywhere in an existing file
ios::binary = Binary mode
ios::in = Input mode used to read data from an existing file
ios::out = Output mode used to write data to a file. If the file does not exist, it
will create it. It also deletes any existing data in a file
ios::trunc = Truncates (deletes) any data in an existing file

Syntax: dataFile.open(info.txt, ios::in)


dataFile.open(info.txt, ios::in | ios::out)
File Operations (continued)
This file is opened for writing This file is opened for reading
using the ofstream data type using the ifstream data type

Writing a file with an ofstream object Reading a file with an ifstream object
File Operations (continued)

It is a good policy to check that the file


exists before trying to open it for
reading. That way, you can handle an
error in a controlled manner.
File Output Formatting
The data can be written to the disk in a formatted
manner
The same formatting techniques are used as with cout
#include <iomanip>
setprecision(n)

fixed

setw(n)
Passing File Stream Objects to Functions
Function Prototypes declare the functions.
Note that the file object must be passed to the
function by reference. (This uses a reference
variable - not a pointer variable)

The file is opened for both reading and writing.


Note that this in in binary mode.

This line calls the read function to print


the existing file data to the screen.

The do loop allows the user to add items


to the file by calling the writefile function.

Here we read the file again and print it to


the screen to view the changes.

Part 1: Function Prototypes and Main( )


Passing File Stream Objects to Functions
Note that the file object is placed in a
reference variable for use in the function

Remember that reference variables are


aliases for the variable it refers to. Thus,
any changes are made to the referenced
variable and we can use it like any other
variable without having to dereference it with
the * operator as with pointers.

Part 2: Function Definitions


More Detailed Error Testing
Stream object contain flag bits that indicate their current
state along with member functions to test the bits:
Flags: Functions:
ios::eofbit Set when the end of an input tream eof() Returns true (nonzero) if the eofbit flag is
is encountered set, otherwise returns false
ios::failbit Set when an attempted operation fail() Returns true (nonzero) if the failbit or
has failed hardfail flags are set, otherwise returns false
ios::hardfail Set when an unrecoverable error bad() Returns true (nonzero) if the badbit flag
has occurred is set, otherwise returns false
ios::badbit Set when an invalid operation has good() Returns true (nonzero) if the goodbit
been attempted flag is set, otherwise returns false
ios::goodbit Set when all the flags above are clear() When called with no oaguments, clears
not set. Indicates the stream is in good all the flags listed above. Can also be called
condition. with a specific flag as an argument.
More Detailed Error Testing (continued)

Example from Chapter 12 in the text.


Member Functions for Reading and Writing
Files
The stream extraction operator >> assumes any
whitespace is a delimiter (just like scanf() does)
The file objects contain member functions to handle
reading an entire line of input including whitespaces
among others
Member functions:
getline() reads an entire line of data including whitespaces
get() reads a single character from the file
put() writes a single character to the file
Member Functions for Reading and
Writing Files (continued)

The getline() reads in an entire


string (including whitespaces) from
the file.

Using the .get() function allows us


to read each character individually.

Note how we can test each character


as it is read from the file.
Working With Multiple Files
We can work with more than one file at a time

Data source file assumed to exist at the


beginning of the program

Copies the data from the source file to the Data destination file which doesnt have
destination file. to exist at the beginning of the program
Binary Files
Use the write() and read() member functions:
fileObject.write(address, size) - address it the starting
address of the memory to be written to the file, size is the
number of bytes of memory to write
fileObject.read(address, size) - address is the starting
address of memory where the data read from the file is to be
stores, size is the number of bytes of memory to read from the
file
The address is assumed to be a pointer to a character so if
the data is not a character, it must be re-cast using the
reinterpret_cast type cast. (e.g. the data is a struct, the struct
pointer must be reinterpret_cast as a char pointer)
The program on the next slide uses the .write() and .read()
member functions.
Creating Records with Structures
Records can be created by writing structures to a file

The file is first opened in write mode to


save the array of structures.

Note how the address of the structure has to be recast


to make it look like a pointer to a character as each
Thing member of the array is written to the file.

After the file is opened in read mode, each of


the Things in the file are read into the
Garbonzo instance of a Thing and printed.
Random-Access Files
seekp() and seekg() member functions are used to
read/write data to any point in a file.
seekp() is the put pointer and seekg() is the get data
position indicator
We move these position indicators relative to either the
beginning of the file (ios::beg), the end of the file
(ios::end), or relative to where we are in the file (ios::cur)
Arguments for the .seekp() and seekg() functions are:
file.seekp(long int offset, mode flag)
file.seekg(long int offset, mode flag)
Random-Access Files (continued)

The previous program has been modified


to place the read position indicators after
the 2nd Thing from the beginning of
the file, then read in the next Thing

The tellg( ) member function gives the


number of bytes that the read position
indicator is into the file.
Opening a File for Both Input and Output
The file is opened for both reading and
writing a binary file.

First, the elements are read from the file


and printed.

Next, we position the read position


indicator at the 3rd element and print it

The data in the 3rd element is edited and


re-written to the file in the same place it
was before. Note the use of the seekp()
function to position the write position
indicator.

You might also like