Reading and writing characters in C++.
Source listing
//---------------------------------------------------------------
// File: Code604_FileIO.cpp
// Purpose: Demonstration of character 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 ch;
outfile.open("textfile.txt", ofstream::out);
//-----------------------------------------------
// Writing characters to a file
// I/O function: outfile.put(char ch)
//-----------------------------------------------
for(ch='a'; ch<='z'; ch++)
{
outfile.put(ch);
}
outfile.close();
//-----------------------------------------------
// Reading characters from a file
// I/O function: char infile.get()
//-----------------------------------------------
infile.open("textfile.txt", ifstream::in);
cout << "Characters read from file.\n";
while (infile.good())
{
ch = infile.get();
cout << ch;
}
cout << "\n";
infile.close();
return 0;
}