#include // istream (e.g. cin) ostream (e.g. cout) stuff #include // file stuff #include // string stuff #include using namespace std; int main(int argc, char* argv[] ) { string fileName = "test.txt"; // a string containing a filename // The ifstream object constructor opens the file (or at least tries to...) // The constructor cannot accept a string object argument, so you have to use // the c_str() method of string to convert the string to an array of characters, // which the constructor will accept. ifstream fileInputStream( fileName.c_str() ); // There are two ways to test whether the ifstream object is actually hooked // to an open file: if( !fileInputStream ) // just check the stream object itself... // if( !fileInputStream.is_open() ) // or use the is_open() method { cerr << "Opening input file " << fileName << " failed!" << endl; exit( EXIT_FAILURE ); } ofstream fileOutputStream( "test.out" ); if( !fileOutputStream.is_open() ) // use the is_open() method { cerr << "Opening output file " << "test.out" << " failed!" << endl; exit( EXIT_FAILURE ); } string strText; // a string used to hold a line of text from the input file while( getline(fileInputStream, strText) ) { fileOutputStream << strText << endl; // echo from input file to output file } fileInputStream.close(); // not needed, would be called automatically... fileOutputStream.close(); // not needed, would be called automatically... return EXIT_SUCCESS; }