Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

06 Advanced File Operations Update

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

06: Advanced File Operations

Programming Technique II
(SCSJ1023)

Adapted from Tony Gaddis and Barret Krupnow (2016), Starting out with
C++: From Control Structures through Objects
Content
 File Operations

 Passing File Stream Objects to Functions

 Member Functions for Reading and Writing Files

 Binary Files

 Random-Access Files
FILE OPERATIONS
File Operations

 A file is a collection of data that is usually stored on a


computer’s disk. Data can be saved to files and then later
reused

 Almost all real-world programs use files to store and


retrieve data extensively:
 Word processing
 Databases
 Spreadsheets
 Compilers
This chapter covers more advanced file operations and
focuses primarily on the fstream data type. Table below
compares the ifstream, ofstream, and fstream
data types. All of these data types require the fstream
header file.
Using Files

 Requires fstream header file


 use ifstream data type for input files
 use ofstream data type for output files
 use fstream data type for both input, output files

 Can use >>, << to read from, write to a file

 Can use eof member function to test for the end of input file.
fstream Object
 The fstream object can be used for either input or output

 Must specify mode on the open statement

 Sample modes:
ios::in – for input files
ios::out – for output files

 Can be combined on open call:


dFile.open("class.txt", ios::in | ios::out);
File Access Flags
Using Files - Example
// copy 10 numbers between files
// open the files

fstream infile("input.txt",ios::in);
fstream outfile("output.txt",ios::out);
int num;

for (int i = 1; i <= 10; i++){


infile >> num; // read from the input file
outfile << num; // write into the output file
}

infile.close(); // close the files


outfile.close();
Default File Open Modes
 ifstream:
 open for input only
 file cannot be written to
 open fails if file does not exist

 ofstream:
 open for output only
 file cannot be read from
 file created if no file exists
 file contents erased if file exists

 The filename used by ifstream, ifstream and fstream objects must be


a c-string (i.e., array of char).
 Thus, if you pass a C++ string, you need to convert it first to a c-string by c_str()
method. Example:

string filename =“input.txt”;


ifstream fin(filename.c_str());
More File Open Details
 Can use filename, flags in definition:
ifstream gradeList("grades.txt");

 File stream object set to NULL or 0 (false) if open failed:


if (!gradeList) ... // This means that it is unable to open the file.
// It is the same meaning as if (gradeList==NULL)

 Can also check fail member function to detect file open


error:
if (gradeList.fail()) ...
PASSING FILE STREAM OBJECTS TO
FUNCTIONS
Passing File Stream Objects to Functions

 It is very useful to pass file stream objects to functions

 Be sure to always pass file stream objects by reference.


Passing File Stream Objects to
Functions

Function call
Program 12-5 (Continued)

Function call

Function definition
Program 12-5 (Continued)

Function definition
Member Functions for Reading
and Writing Files
Member Functions for Reading and
Writing Files

 Functions that may be used for input with whitespace, to


perform single character I/O, or to return to the beginning of
an input file

Member functions:
getline: reads input including whitespace
get: reads a single character
put: writes a single character
getline Method
For working with C-strings. Three arguments needed:
 A c-string (i.e., character array) to hold input

 Number of characters to read

 Terminator (or delimiter) to stop at if encountered before


number of characters was read in

 '\n' is the default delimiter (i.e, for the third argument)

 Example:
ifstream myFile(“input.txt”);
char name[41], addr[41];
myFile.getline(name, 40); //using default delimiter ‘\n'
myFile.getline(addr, 40, '\t');
getline Member Function
getline function
For working with C++ strings
 Prototype:
getline(fileObject, stringBuffer, delimiter);

 '\n' is the default delimiter (i.e, for the third argument)

 Examples:
ifstream myFile(“input.txt”);
string name,addr;
getline(myFile, name); // using default delimiter ‘\n'
getline(myFile, addr, '\t');
getline Function
Input file

Screen output
Example of using different delimiters
Input file

Screen output
Single Character I/O
 get: to read a single character from an input file.
Example:
ifstream gradeFile(“grade.txt”);
char letterGrade;
gradeFile.get(letterGrade);
 Will read any character, including whitespace

 put: to write a single character to an output file.


Example:
ofstream reportFile(“report.out”);
char letterGrade;
…..
…..
reportFile.put(letterGrade);
BINARY FILES
Binary Files
Binary files contain unformatted and non-human-
readable data.

Specified by using a binary flag on open:


Example:

inFile.open("nums.dat", ios::in|ios::binary);
Binary Files
Use read instead of <<, to read data from files.
Example: To read a letter from an input file
fstream fin(“input.dat“,ios::in|ios::binary);
char ch;
fin.read(&ch, sizeof(ch));

First parameter: the address of


where to put the data being read Second parameter: how
in. many bytes to read from the
file.
The function expects the data
variable as char .

Thus, if other than char, it must


be type casted.
Binary Files
Use write instead of >> to write data into files.
Example: To write a letter into an output file
fstream fout(“report.out“,ios::out|ios::binary);
char ch;
….
….
fout.write(&ch, sizeof(ch));

First parameter: the address of Second parameter: how


where to get the data from.
many bytes to write to the
The function expects the data
file.
variable as char .

Thus, if other than char, it must


be type casted.
Binary Files
 To read and write non-character data, must use a typecast operator
to treat the address of the data as a character address

Example: To read an integer from a file


fstream fin(“number.dat“,ios::in|ios::binary);
int num;
fin.read(reinterpret_cast<char *>&num, sizeof(num));

treat the address of num as


the address of a char

 Or simply use C-style casting

fin.read((char *)&num, sizeof(num));


Binary Files
Example: To write an integer into a file
fstream fout(“number.dat“,ios::out|ios::binary);
int num;
cin >> num; // getting a number from the keyboard

fout.write(reinterpret_cast<char *>&num, sizeof(num));

C-style:
fout.write((char *)&num, sizeof(num));
Example Application of Binary Files
Copying a file
Example Application of Binary Files
Writing and reading an object into/from a file
Example Application of Binary Files
Writing an array of objects into a file (1)
Example Application of Binary Files
Writing an array of objects into a file (2)
Example Application of Binary Files
Reading an array of objects from a file (1)

Screen output
Example Application of Binary Files
Reading an array of objects from a file (2)

Screen output
RANDOM-ACCESS FILES
Random-Access Files

Sequential access: start at beginning of file


and go through data in file, in order, to end
to access 100th entry in file, go through 99
preceding entries first

Random access: access data in a file in any


order
can access 100th entry directly
Random Access Member Functions

 seekg (seek get): used with input files.

 seekp (seek put): used with output files.

 Used to go to a specific position in a file


Random Access Member Functions
 seekg,seekp arguments:
offset: number of bytes, as a long
mode flag: starting point to compute offset

Examples:
inData.seekg(25L, ios::beg);
// set read position at 26th byte
// from beginning of file

outData.seekp(-10L, ios::cur);
// set write position 10 bytes
// before current position
Important Note on Random Access

 If eof is true, it must be cleared before seekg or seekp:

Example:
gradeFile.clear();

gradeFile.seekg(0L, ios::beg);
// go to the beginning of the file
Random Access Information
 tellg member function: return current byte position in
input file
Example:
long int whereAmI;
whereAmI = inData.tellg();

 tellp member function: return current byte position in


output file
Example:

whereAmI = outData.tellp();
Example Application of Random-Access
Determining the size of a file

You might also like