/********************************************************************** * fileopen.cc * Tom Kelliher * * This program demonstrates how to open a file whose name isn't known * until runtime. Two file are opened, one for reading and one for * writing. The files are immediately closed (no I/O is done). **********************************************************************/ #include #include const int NAME_LEN = 80; // Prototypes. int queryOpen(const char*, fstream&, int); /********************************************************************** * main **********************************************************************/ int main() { fstream f1, f2; // Two files. Note that they're fstream, not // ifstream nor ofstream. // Open files and check for success. if (!queryOpen("Input file to open: ", f1, ios::in)) cout << "f1 failed\n"; if (!queryOpen("Output file to open: ", f2, ios::out)) cout << "f2 failed\n"; /* We could begin doing things like: f1 >> i; f1.getline(char_array, length); f2 << "Hello world!\n"; */ f1.close(); f2.close(); return 0; } /********************************************************************** * queryOpen --- Print a message, read a filename to open from cin and * try to open it. * mesg: A string to print before reading the filename from cin. * f: The fstream variable to which to bind the file. * mode: ios::in to open for reading, ios::out for writing, etc. * * return value: 1 if successful in opening the file, 0 otherwise. **********************************************************************/ int queryOpen(const char* mesg, fstream& f, int mode) { char name[NAME_LEN]; cout << mesg; cin.getline(name, NAME_LEN); // Read filename. f.open(name, mode); return !f.fail(); }