Lab 11 File Handling
Lab 11 File Handling
inputFile.open("Customers.txt");
Creating a File Object and Opening a
File
• The following code shows an example of opening a file for output
(writing).
ofstream outputFile;
outputFile.open("Employees.txt");
• The first statement defines an ofstream object named outputFile. The
second statement calls the object’s open member function, passing
the string "Employees.txt" as an argument. In this statement, the
open member function creates the Employees.txt file and links it with
the outputFile object
Creating a File Object and Opening a
File
• Often, when opening a file, you will need to specify its path as well as
its name. For example, on a Windows system the following statement
opens the file C:\data\inventory.txt:
inputFile.open("C:\\data\\inventory.txt")
• In this statement, the file C:\data\inventory.txt is opened and linked
with inputFile
• To define a file stream object and open a file in one statement.
ifstream inputFile("Customers.txt");
ofstream outputFile("Employees.txt");
Closing a File
• The opposite of opening a file is closing it. Although a program’s files
are automatically closed when the program shuts down, it is a good
programming practice to write statements that close them
• Calling the file stream object’s close member function closes a file.
Here is an example:
inputFile.close();
Writing Data to a File
// This program writes data to a file.
#include <iostream>
#include <fstream>
using namespace std; // Close the file
outputFile.close();
int main()
{ cout << "Done.\n";
ofstream outputFile;
outputFile.open("demofile.txt"); return 0;
}
cout << "Now writing data to the file.\n";
• Keep in mind that when the >> operator extracts data from a file, it
expects to read pieces of data that are separated by whitespace
characters (spaces, tabs, or newlines)
Reading Numeric Data From a
Text
file.
File
// This program reads numbers from a // Calculate the sum of the numbers.
#include <iostream> sum = value1 + value2 + value3;
#include <fstream>
using namespace std; // Display the three numbers.
int main() cout << "Here are the numbers:\n"
{ << value1 << " " << value2
ifstream inFile; << " " << value3 << endl;
int value1, value2, value3, sum;
// Open the file. // Display the sum of the numbers.
inFile.open("NumericData.txt"); cout << "Their sum is: " << sum << endl;
return 0;
// Read the three numbers from the file.
}
inFile >> value1;
inFile >> value2; Program Output
inFile >> value3; Here are the numbers:
10 20 30
// Close the file.
inFile.close(); Their sum is: 60
Using Loops to Process Files
Using Loops to Process Files
// This program reads data from a file. // Close the file.
#include <iostream> inputFile.close();
#include <fstream> return 0;
using namespace std; }
int main()
{
ifstream inputFile;
int number;
// Open the file.
inputFile.open("ListOfNumbers.txt");
// Read the numbers from the file and
// display them.
while (inputFile >> number)
{
cout << number << endl;
}
Lab Task
Good Luck