COSC 1315

Programming Fundamentals

Simple File I/O

Revised:  February 5, 2007
By Richard G. Baldwin

File:  Pf 00200.htm
Practice Text

 


Preface

This lesson was written specifically for the benefit of my students in COSC 1315, Fundamentals of Programming.  The lesson was written under the assumption that those students have no prior programming knowledge when they enroll in the course.

Another browser window

I recommend that you open another copy of this document in a separate browser window so that you can view the code and the discussion of that code at the same time.

Introduction

Reading and writing files

The purpose of this lesson is to teach you how to read and write simple files in C++ and how to use those files in conjunction with arrays.  I will present and explain a C++ program named File01.

The program reads five numbers from an input file and stores them in reverse order in an array of type long.  That is to say, the program stores the first value read from the file into the array element at index 4 and stores the last value read from the file into the element at index 0.

Then the program displays the five values in forward order on the screen relative to the beginning of the array.  Then it writes the contents of the array into an output file in forward order.

Following this, the program computes and displays the average of the three middle values in the array.

Finally, the program closes the input file and the output file.

Program output

Figure 1 shows the program output for a typical input file:

SAMPLE INPUT AND OUTPUT VALUES:

For a file containing the following input values:

-100 -50 0 49 99

The output file contains the following values:

99 49 0 -50 -100

and the screen output while the program is running is:

Array contents:
99 49 0 -50 -100
Avg 3 middle values = -0.333333

Figure 1

As you can see, the order of the values in the output file are reversed relative to the order of the values in the input file.

Also, the average value of the middle three values is computed by discarding the first and the last of the five values read from the input file.

Sample Program

In this lesson, I will present and explain a C++ program named File01.  I will explain the program in fragments.  You can view a complete listing of the program in Listing 7 near the end of the lesson.

Two of the functions in the program, main and classMain, are identical to functions having the same names in sample programs in previous lessons.  Therefore, I won't explain those functions in this lesson.

The function named doSomething

All of the new and interesting code in this program is contained in an instance function named doSomething.  The beginning of the program, the beginning of the class, and the beginning of the function named doSomething are all shown in Listing 1.

#include <iostream>
#include <fstream>//required for file operations
using namespace std;

class File01{ 
  public:
  static void classMain(){
    //code deleted for brevity
  }//End classMain function
  //-----------------------------------------------------//

  //An instance function of the File01 class
  void doSomething(){
    ifstream dataFile;//Input file stream
    ofstream outFile;//Output file stream

    dataFile.open("File01in.txt");//Input file name
    outFile.open("File01out.txt");//Output file name

    const int size = 5;
    long values[size];
  
Listing 1

A new include file

Listing 1 shows that you must include the file named fstream in order to perform file I/O in C++.  (This is the first time that this file has been included in this series of tutorial lessons.)

Input and output file streams

The first two statements in the doSomething function declare variables of the classes ifstream and ofstream, which will be used to provide input and output file stream capability respectively.

The next two statements in the doSomething function associate those two I/O streams with the physical files named File01in.txt and File01out.txt respectively.

Prepare the array

The last two statements shown Listing 1 prepare for the use of an array of type long containing five elements.  This is not new.  Code like this was used in the earlier lesson entitled One-Dimensional Arrays.

Read the input file

Listing 2 applies the extraction operator to the input file stream object named dataFile to read five values from the file and to store them in the five elements of the array in reverse order.

    int count = size - 1;
    while(count >= 0){
      dataFile >> values[count];
      count = count - 1;
    }//end while loop
  
Listing 2

You saw code similar to this in the earlier lesson entitled One-Dimensional Arrays.  In that lesson, the five values were read from the keyboard instead of being read from a file.  However, if you compare the code in Listing 2 above to the code in Listing 3 in the earlier lesson, you will see that there is very little difference in reading data from the keyboard and reading data from a file once the file is opened for reading as shown in Listing 1.

Display the array data

Listing 3 displays the array data in forward order.

    cout << "Array contents:" << endl;
    count = 0;
    while(count < size){
      cout << values[count] << " ";
      count = count + 1;
    }//end while loop
    cout << endl;
  
Listing 3

Once again, you saw code similar to this in the earlier lesson entitled One-Dimensional Arrays.

Write the array data into the output file

Listing 4 writes the array data into the output file in forward order by applying the insertion operator to the file output stream object named outFile,

    count = 0;
    while(count < size){
      outFile << values[count] << " ";
      count = count + 1;
    }//end while loop
    outFile << endl;
  
Listing 4

Note the similarity of the code in Listing 4 to the code in Listing 3.  As you can see, reading and writing data to a file isn't much different from reading data from the keyboard and writing data to the computer screen.

Compute and display an average value

Listing 5 computes and displays the average value of the three middle values that were read from the file and stored in the array.  This code is straightforward.

    count = 1;
    double sum = 0;
    while(count < size-1){
      sum = sum + values[count];
      count = count + 1;
    }//end while loop
    cout << "Avg 3 middle values = " << sum/(size - 2) 
  
Listing 5

The only reason that I included this code in this lesson is because the ACC Master Syllabus for this course states that the course is to include the topic "Using only part of an array."

Close the files

Listing 6 invokes the close method on both of the file I/O stream objects to flush the output buffers, disassociate the stream objects from the two specific files, etc.

    dataFile.close();
    outFile.close();
  }//end doSomething function
  
Listing 6

So now you know how to read and write data from files in C++ and how to use that data in conjunction with arrays, which is another requirement of the Master Syllabus for this course.

Complete Program Listing

A complete listing of the program discussed in this lesson is shown below.
 
/*File:  File01.cpp
This C++ program illustrates the use of input and output
files in conjunction with arrays.

The program reads five numbers from an input file and 
stores them in reverse order in an array of type long.
That is to say, it stores the first value read in the 
element at index 4 and stores the last value read in the
element at index 0.

Then it displays the five values in forward order relative
to the beginning of the array.

Then it writes the contents of the array into an output
file in forward order.

Then it computes and displays the average of the three
middle values in the array.

Finally, it closes the input file and the output file.

SAMPLE INPUT AND OUTPUT VALUES:

For a file containing the following input values:

-100 -50 0 49 99

The output file contains the following values:

99 49 0 -50 -100

and the screen output while the program is running is:

Array contents:
99 49 0 -50 -100
Avg 3 middle values = -0.333333

**********************************************************/

#include <iostream>
#include <fstream>//required for file operations
using namespace std;

class File01{ 
  public:
  static void classMain(){
    File01* ptrToObject = new File01();
    ptrToObject -> doSomething();
  }//End classMain function
  //-----------------------------------------------------//

  //An instance function of the File01 class
  void doSomething(){
    ifstream dataFile;//Input file stream
    ofstream outFile;//Output file stream
    dataFile.open("File01in.txt");//Input file name
    outFile.open("File01out.txt");//Output file name

    const int size = 5;
    long values[size];

    //Populate the array in reverse order by reading data
    // values from an input file..
    int count = size - 1;
    while(count >= 0){
      dataFile >> values[count];
      count = count - 1;
    }//end while loop

    //Display contents of the array in forward order.
    cout << "Array contents:" << endl;
    count = 0;
    while(count < size){
      cout << values[count] << " ";
      count = count + 1;
    }//end while loop
    cout << endl;

    //Write array data into the output file in forward 
    // order.
    count = 0;
    while(count < size){
      outFile << values[count] << " ";
      count = count + 1;
    }//end while loop
    outFile << endl;

    //Compute and display the average of the three middle 
    // values in the array.
    count = 1;
    double sum = 0;
    while(count < size-1){
      sum = sum + values[count];
      count = count + 1;
    }//end while loop
    cout << "Avg 3 middle values = " << sum/(size - 2) 
                                                   << endl;

    //Close both files.
    dataFile.close();
    outFile.close();
  }//end doSomething function
  //-----------------------------------------------------//

};//End File01 class
//-------------------------------------------------------//

int main(){
  File01::classMain();
  return 0;
}//end main

Listing 7


Copyright 2005, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-