ofstream outfile("output.txt"); |
ifstream infile("input.txt"); |
#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 streaminfile2>>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 |