PF-Lecture 27 File Handling
PF-Lecture 27 File Handling
File Handling
Using Files for Data Storage
2
Using Files
3
Files: What is Needed
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
6
File Access Flags
7
Testing for File Open Errors
if (infile.fail()) ...
8
Using Files - Example
• 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
12
Closing Files
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
17
18
Program 12-3 (Continued)
19
Passing File Stream Objects to Functions
20
21
22
23
More Detailed Error Testing
24
Member Functions / Flags
25
From Program 12-6
26
Member Functions for Reading and Writing Files
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');
28
29
30
Single Character I/O
31
Working with Multiple Files
32
33
34
35
Binary Files
36
Binary Files
37
Binary Files
39
Random Access Member Functions
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
gradeFile.clear();
gradeFile.seekg(0L, ios::beg);
// go to the beginning of the file
42
Random Access Information
43
Opening a File for
Both Input and Output
44
Thank you