Monday, November 7, 2011

File access and user input

Usually you don't want to hard-code filenames into your projects: you want to let the user decide what the filenames should be. Here is an easy way to do just that.

First, make sure you include both fstream and iomanip.

#include <fstream>
#include <iomanip>


In your main or other file accessing function, request an input filename from the user.

string inputFilename;
cout << "Enter input filename: ";
cin >> inputFilename;


Attempt to open the file.

ifstream fin;
fin.open(inputFilename.c_str());


Check to see that the file does indeed exist. If it doesn't, you should tell the user and beat a hasty retreat.

if ( !fin )
{
   cout << inputFilename << " does not exist.\n";
   fin.close();
}


Oh, so you want to write a file, now, do you?

string outputFilename;
cout << "Enter output filename: ";
cin >> outputFilename;

ofstream fin;
fin.open(outputFilename.c_str());


And one more thing: always remember to close your files before leaving the program!

fin.close();
fout.close();