Reading and writing strings in C++.


Source listing
//---------------------------------------------------------------
// File: Code605_FileIO.cpp
// Purpose: Demonstration of string I/O in ANSI Standard C++
// Programming Language: C++
// Author: Dr. Rick Coleman
//---------------------------------------------------------------
#include <fstream>

using namespace std;

int main(void)
{
    ofstream outfile;    // Output file stream
    ifstream infile;    // Input file stream
    char line[81];     // Use 80 char lines

    outfile.open("textfile.txt", ofstream::out);
    //-----------------------------------------------------------
    //  Writing strings to a file
    //  I/O function:  outfile.write(char *string, int numChars)
    //-----------------------------------------------------------
    for(int i=0; i<10; i++)
    {
        outfile.write("Testing writing to file\n", 24);
    }
    outfile.close();

    infile.open("textfile.txt", ifstream::in);
    //-----------------------------------------------------------
    //  Reading strings from a file
    //  I/O function:  infile.getline(char *string, int maxChars)
    //-----------------------------------------------------------
    while (infile.good())
    {
        infile.getline(line, 80);  
        cout << line << "\n"; 
    }
    infile.close();
    return 0;
}