File Input/Output in C++

Estimated read time 6 min read

In earlier sections, we explored how to receive input from the keyboard (the standard input device) and how to display output on the screen (the standard output device). While these methods are convenient for small amounts of data, they become inefficient and cumbersome when dealing with larger datasets. Moreover, when you need to share output with others, simply displaying it on a screen is often not enough.

When handling large volumes of input, typing everything manually from the keyboard is not practical. Not only is it time-consuming, but it also increases the likelihood of errors due to typos. To avoid these issues, data can be prepared in advance and stored in files, allowing the program to access it whenever needed.

Similarly, if you need to present program output during a meeting, distributing printed copies of the output is often more effective than displaying it on a screen. For instance, handing out a report to each committee member before a meeting ensures that everyone has access to the information. Additionally, sometimes it is necessary to save the output for future use, such as when one program’s output is used as input for another.

This section will discuss how to handle data input from external sources like a flash drive (secondary storage) and how to save output back to these devices. C++ allows you to directly read from and write to files stored on secondary storage. A file, in this context, is simply an area in secondary storage that holds information.

Working with Files in C++

To work with files in C++, you’ll need to use the <fstream> header file, which provides the necessary tools for file input/output (I/O). While the <iostream> header file is used for standard I/O operations with the keyboard and screen, <fstream> offers additional functionality for handling files. It includes the definitions for two important data types: ifstream (input file stream) and ofstream (output file stream), which are similar to istream and ostream used for standard I/O.

Steps for File I/O in C++

File I/O in C++ involves five main steps:

  1. Include the <fstream> Header File: This header file must be included in your program to use file stream objects.
   #include <fstream>
  1. Declare File Stream Variables: These variables will be used to read from and write to files. For example:
   ifstream inData;
   ofstream outData;

Here, inData is an input file stream variable, and outData is an output file stream variable.

  1. Open the Files: This step involves associating the file stream variables with the actual files. This is done using the open function.
   inData.open("prog.dat");  // Open the input file
   outData.open("prog.out"); // Open the output file

If the input file prog.dat is in a different directory, you’ll need to specify the full path.

  1. Use the File Stream Variables for I/O Operations: You can use the file stream variables with operators like >> and << in the same way you would use cin and cout.
   inData >> payRate;    // Read data from prog.dat into payRate
   outData << "The paycheck is: $" << pay << endl;  // Write output to prog.out
  1. Close the Files: After completing the I/O operations, you should close the files to free up resources and ensure that all output is written to the file.
   inData.close();  // Close the input file
   outData.close(); // Close the output file

Opening and Closing Files

Opening a file connects the file stream variable in your program to the actual file on your storage device. For input files, the file must exist before it can be opened; otherwise, the open operation will fail, and the input stream will enter a fail state. Output files, on the other hand, do not need to exist beforehand; if they do not, an empty file will be created. If the output file already exists, its contents will be overwritten by default when the file is opened.

Example: Movie Tickets Sale Program

Let’s consider a practical example where a movie theater owner wants to donate a portion of ticket sales to charity. The program prompts the user to input details like the movie name, ticket prices, and the number of tickets sold, and it calculates the total sales, the amount to be donated, and the net sales. The results are then saved to a file.

The steps for this program include reading input data, performing calculations, and writing the results to an output file. Here’s how the process works:

  1. Input: The user enters the movie name, ticket prices, the number of tickets sold, and the percentage of sales to be donated.
  2. Processing: The program calculates the total sales, the donation amount, and the net sales.
  3. Output: The results are written to an output file, formatted with the necessary precision and alignment.

Example Code

Below is a simplified version of the movie ticket program:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main() {
    // Declare variables
    string movieName;
    double adultTicketPrice, childTicketPrice, grossAmount, amountDonated, netSales;
    int adultTicketsSold, childTicketsSold;
    double percentDonation;

    // Open files
    ifstream inFile("input.txt");
    ofstream outFile("output.txt");

    // Input data from file
    getline(inFile, movieName);
    inFile >> adultTicketPrice >> childTicketPrice >> adultTicketsSold >> childTicketsSold >> percentDonation;

    // Calculate amounts
    grossAmount = (adultTicketPrice * adultTicketsSold) + (childTicketPrice * childTicketsSold);
    amountDonated = grossAmount * (percentDonation / 100);
    netSales = grossAmount - amountDonated;

    // Output results to file
    outFile << fixed << showpoint << setprecision(2);
    outFile << "Movie Name: " << movieName << endl;
    outFile << "Gross Amount: $" << grossAmount << endl;
    outFile << "Amount Donated: $" << amountDonated << endl;
    outFile << "Net Sales: $" << netSales << endl;

    // Close files
    inFile.close();
    outFile.close();

    return 0;
}

Conclusion

File I/O in C++ provides a powerful way to manage data by reading from and writing to files, making your programs more versatile and capable of handling larger datasets efficiently. By following the five-step process outlined above, you can incorporate file handling in your C++ programs, enabling you to store inputs and outputs in files for future reference, analysis, or distribution.

+ There are no comments

Add yours