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

PF-Lecture 27 File Handling

Uploaded by

fahadnae123
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 views

PF-Lecture 27 File Handling

Uploaded by

fahadnae123
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
You are on page 1/ 45

CS 1002 Programming Fundamentals

Lecture 27 Nov 2022

File Handling
Using Files for Data Storage

• Can use files instead of keyboard, monitor screen for program


input, output
• Allows data to be retained between program runs
• Steps:
– Open the file
– Use the file (read from, write to, or both)
– Close the file

2
Using Files

1. 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
2. Can use >>, << to read from, write to a file
3. Can use eof member function to test for
end of input file

3
Files: What is Needed

• Use fstream header file for file access


#include <fstream>
• File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
• Define file stream objects:
ifstream infile;
ofstream outfile;

4
Opening Files

• Create a link between file name (outside the program) and file
stream object (inside the program)
• Use the open member function:
infile.open("inventory.dat");
outfile.open("report.txt");
• Filename may include drive, path info.
• Output file will be created if necessary; existing file will be
erased first
• Input file must exist for open to work

5
fstream Object

• fstream object can be used for either input or output


• Must specify mode on the open statement
• Sample modes:
ios::in – input
ios::out – output
• Can be combined on open call:
fstream dFile;
dFile.open("class.txt", ios::in | ios::out);

6
File Access Flags

7
Testing for File Open Errors

• Can test a file stream object to detect if an open operation failed:


infile.open("test.txt");
if (!infile)
{
cout << "File open failure!";
}
• Can also use the fail member function

if (infile.fail()) ...

8
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; // use the files
outfile << num;
}
infile.close(); // close the files
outfile.close();
9
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

10
Using Files

• Can use output file object and << to send data to a file:
outfile << "Inventory report";
• Can use input file object and >> to copy data from file to
variables:
infile >> partNum;
infile >> qtyInStock >> qtyOnOrder;

11
Using Loops to Process Files

• The stream extraction operator >> returns true when a


value was successfully read, false otherwise

• Can be tested in a while loop to continue execution as


long as values are read from the file:
while (inputFile >> number) ...

12
Closing Files

• Use the close member function:


infile.close();
outfile.close();
• Don’t wait for operating system to close files at program
end:
– may be limit on number of open files
– may be buffered output data waiting to send to file

13
Letting the User Specify a Filename

• In many cases, you will want the user to specify the name
of a file for the program to open.
• In C++ 11, you can pass a string object as an argument
to a file stream object’s open member function.
• Test if the open(filename) call fails using:
infile.open(filename);
if (infile.failed()) {
cout << “Filename “ << filename << “ cannot be
opened.” << endl;
return 0; // can also use exit(1);
}

14
Letting the User Specify a Filename in Program

Continued…

15
Letting the User Specify a Filename in Program

16
File Output Formatting

• Use the same techniques with file stream objects as with


cout: showpoint, setw(x), showprecision(x),
etc.

• Requires iomanip to use manipulators

17
18
Program 12-3 (Continued)

19
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

20
21
22
23
More Detailed Error Testing

• Can examine error state bits to determine stream


status
• Bits tested/cleared by stream member functions
ios::eofbit set when end of file detected
ios::failbit set when operation failed
ios::hardfail set when error occurred and no recovery
ios::badbit set when invalid operation attempted
ios::goodbit set when no other bits are set

24
Member Functions / Flags

eof() true if eofbit set, false otherwise

fail() true if failbit or hardfail set, false otherwise

bad() true if badbit set, false otherwise

good() true if goodbit set, false otherwise

clear() clear all flags (no arguments), or clear a specific flag

25
From Program 12-6

26
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

27
The getline Function

• Three arguments:
– Name of a file stream object
– Name of a string object
– Delimiter character of your choice
– Examples, using the file stream object myFile,
and the string objects name and address:
getline(myFile, name);
getline(myFile, address, '\t');

– If left out, '\n' is default for third argument

28
29
30
Single Character I/O

• get: read a single character from a file


char letterGrade;
gradeFile.get(letterGrade);
Will read any character, including whitespace

• put: write a single character to a file


reportFile.put(letterGrade);

31
Working with Multiple Files

• Can have more than file open at a time in a program

• Files may be open for input or output

• Need to define file stream object for each file

32
33
34
35
Binary Files

• Binary file contains unformatted, non-ASCII data


• Indicate by using binary flag on open:
inFile.open("nums.dat", ios::in | ios::binary);

36
Binary Files

• Use read and write instead of <<, >>


char ch;
// read in a letter from file
inFile.read(&ch, sizeof(ch));

address of where to put


the data being read in. how many bytes to
The read function expects
read from the file
to read chars

// send a character to a file


outFile.write(&ch, sizeof(ch));

37
Binary Files

• To read, write non-character data, must use a


typecast operator to treat the address of the data
as a character address
int num;
// read in a binary number from a file
inFile.read(reinterpret_cast<char *>&num,
treat the address of num as sizeof(num));
the address of a char

// send a binary value to a file


outf.write(reinterpret_cast<char *>&num,
sizeof(num));
38
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

39
Random Access Member Functions

• seekg (seek get): used with files open for input

• seekp (seek put): used with files open for output

• Used to go to a specific position in a file

40
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

41
Important Note on Random Access

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

gradeFile.clear();
gradeFile.seekg(0L, ios::beg);
// go to the beginning of the file

42
Random Access Information

• tellg member function: return current byte position in input file


long int whereAmI;
whereAmI = inData.tellg();

• tellp member function: return current byte position in output


file
whereAmI = outData.tellp();

43
Opening a File for
Both Input and Output

• File can be open for input and output simultaneously


• Supports updating a file:
– read data from file into memory
– update data
– write data back to file
• Use fstream for file object definition:
fstream gradeList("grades.dat",
ios::in | ios::out);
• Can also use ios::binary flag for binary data

44
Thank you

You might also like