C++: Example - File open dialog
Example of file open dialog
When you aren't using a GUI,
you can make a simple text-based file open dialog with something like the following
code. A portability problem with this code is that
the default directory depends on the settings of the I/O library that you're using.
The system I'm using defaults to the directory where the object
program is located, but results will vary.
#include <fstream>
using namespace std;
. . .
//--- select and open file
ifstream fin; // The new file stream.
string filename; // Where to read file name.
do {
cout << "Enter input data file name:";
cin >> filename; // Get the file name.
fin.open(filename.c_str()); // Convert to C-string and open it.
if (!fin) { // Will fail if didn't exist.
cout << "Unable to open " << filename << endl;
}
} while (!fin); // Continue until good file.
while (fin >> . . .
. . .
fin.close();
Parameter to open
must be a C-string
The call to open
takes a file name parameter.
It must be a C-string (type char *
), not type
string
. The example above illustrates
the use of the c-str()
function which returns
a C-string from a string.