C++

Back to C++ main page

File I/O

To read from or write to a file, you must declare a stream type. First, place these libraries in the include block:
#include<fstream.h> //opens file streams
#include<iomanip.h> //alows stream manipulation

For writing to files the declaration is: ofstream streamname("filename"); Example:
ofstream outfile("output.txt");

For reading from files the declaration is: ifstream streamname("filename"); Example:
ifstream infile("input.txt");
These only create the streams, the actual read an writes are done like this:
#include<fstream.h>
#include<iomanip.h>
#include <iostream.h>
#include <stdio.h>


void main(){

ifstream infile("input.txt"); //Create a simple text file with a few lines for testing, will error out otherwise
ofstream outfile("output.txt"); //Will be created if it does not exist, will be overwritten if it does exist
char oneChar; //declare a char that will hold the file data, one char at a time

infile>>oneChar; //using the stream declared above get the first char in the file

while(!infile.eof()){

cout<<oneChar;
infile>>oneChar;

}

/* Using a while loop we print out the contents of a file one at a time. A character is printed and a new character is taken from from the file stream. The condition in the while loop, !infile.eof(), means: keep doing this until we reach the end of the file. the ! "not", infile is our file stream, eof() is a function that determines if we have reached the end of the file. */

infile.close; //close the file stream when we're done

/* The following is a variation on the above that reads from one file and writes the contents to another file. Basically, we substitute cout with the name of our write file stream: outfile.*/

ifstream infile2("input.txt"); //create a new stream
infile2>>oneChar;

while(!infile2.eof()){

outfile<<oneChar;
infile2>>oneChar;

}

infile2.close; //close the file stream when we're done
outfile.close; //close the file stream when we're done

}//end main


Links

Overview of the C++ I/O Class Library
C++ I/O
Advanced File Operations

C++ I/O
File Processing
Using cin.ignore()
C++ ASCII chars
File Streams
Character conversion and testing
General C++