Site icon TestingDocs.com

Read and Write Files in C++ program

Overview

In this post, we will write simple C++ programs to read and write files. In order to input and output to a file, we need to use the standard header file ifstream.

ifstream/ofstream

Suppose if we need an input stream to read values from the file, we can create an ifstream object that uses the file. ifstream fin(“sample.txt”); Similarly, we can use ofstream object to write data to a file. ofstream fout(“output.txt”); Let’s write a simple program to read numbers from a file and calculate the sum of the numbers that are in the file called ‘input.txt’. Create a file with the name and enter some numbers. For example, below input file. 10.5 21.5 64.0 96.5

Code Listing:File Input

C++ program to read and calculate the sum of numbers.

/**************************************
* C++ File input demo program
**************************************/

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

int main()
{
    double sum = 0.0;
    double x;
    ifstream inFile;

    inFile.open("input.txt");
    if (!inFile)
    {
        cout << "Unable to open file";
        exit(1);
    }

    while (inFile >> x)
    {
        sum = sum + x;
    }

    inFile.close();
    cout << "Sum of numbers in the file is = " << sum << endl;
    return 0;
}

Output: Sum of numbers in the file is = 192.5

Process returned 0 (0x0) execution time : 0.436 s Press any key to continue.

C++ program output

 

The while loop iterates until there are no more numbers to read from the stream inFile. If the file initialization is not successful, an error message is displayed and the program is exited. The close() function is usually called after processing of the file is complete.

Code Listing: File Output

Let’s write the output to a file using the program shown below. A new output file would be created with the output written to the file.

/**************************************
* C++ File input/output demo program
**************************************/

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;

int main()
{
    double sum = 0.0;
    double x;
    ifstream inFile;
    ofstream outFile;

    inFile.open("input.txt");
    if (!inFile)
    {
        cout << "Unable to open input file";
        exit(1);
    }
    outFile.open("output.txt");
    if (!outFile)
    {
        cout << "Unable to open output file";
        exit(1);
    }
    while (inFile >> x)
    {
        sum = sum + x;
    }

    outFile << "Sum of numbers in the file is = " << sum << endl;
    inFile.close();
    outFile.close();
    return 0;
}

 

The IDE used in the program is Code:: Blocks. To download and install Code Blocks follow the link:

https://www.testingdocs.com/download-and-install-codeblocks/

For more information on Code Blocks IDE, visit the official website of Code blocks IDE: http://www.codeblocks.org/

Exit mobile version