Writing to Files

Syntax

Writing to a file is done in almost the same way as reading from a file.  The equivalent command to the ifstream declaration that opens a file for writing is:

ofstream streamname("filename.txt");

The only difference is that the variable is declared as ofstream instead of ifstream.  The other change is that the extraction (<<) operator is used to output the text to the file (instead of using the insertion >> operator), as shown here:

streamname<<data;

A simple program that outputs the numbers 1 to 10 to a file is shown here:

#include <iostream.h>

#include <fstream.h>



void main(void)

{

    ofstream out;

    int i;

	

    out.open("temp.txt");

    for(i=1;i<=10;i++)

    {

        out<<i<<endl;

    }

}

Implementation

Implementing file output in a program is complicated by the fact that any time a file is opened for writing it completely erases the file.   This means that if you want to change file, you need to read it in, store all of the information, make the necessary changes and rewrite it to a file.  If you have a file with 5 names in it, and you need to change the third one to "Eric" you would do so as follows:

#include <iostream.h>

#include <fstream.h>

#include <apvector.h>

#include <apstring.h>



void main(void)

{

    int i;

    apvector<apstring> names(5);

    ifstream in;

    ofstream out;

    

    in.open("temp.txt");

    for(i=0;i<=4;i++)

    {

        in>>names[i];

    }

    in.close();



    names[2]="Eric";



    out.open("temp.txt");

    for(i=0;i<=4;i++)

    {

        out<<names[i]<<endl;

    }

    out.close();

}

Note the use of arrays that was necessary to read in all of the names and store them temporarily.  This is the key to changing data in a file.

Assignment

Given the above information on writing to files add the ability to your gradechecker program to change a grade.  The program should prompt for which person's grade you want to change, which grade (e.g. first, second, third...) you want to change, and what the new grade is.  The program should ask for a teacher password to allow for these grade changes.  You may also add the ability to add users or add to the number of grades in the file once you have the ability to change grades.

Back to Home Page House3.wmf (25540 bytes)