Prompting user for filename to be opened for simple data processing C++ source code sample

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Opening a text file for data processing by prompting the file name from user (read from standard input) in C++ programming

To show: How to open a text file for data processing by prompting the file name from user (read from standard input) in C++ programming

 

// prompting user for filename to be opened. Others should be similar to the previous example.

#include <iostream>

#include <fstream>

using namespace std;

 

void main(void)

{

char filename[100];

ifstream inputfile;

 

// prompting user for filename to be opened including the full path if necessary

// e.g. c:\testfileio.txt, c:\\Windows\\Temp\\testfile.txt etc

cout<<"Enter the file name to be opened: ";

// read and store in an filename array. Array without [ ] is a pointer to the first array's element

cin>>filename;

 

// opened a file for input

inputfile.open(filename, ios::in);

 

// test if fail to open file for reading

if(inputfile.fail())

{

cout<<"Opening "<<filename<<" file for reading\n";

cout<<"---------------------------------------\n";

cout<<"The "<<filename<<" file could not be opened!\n";

cout<<"Possible errors:\n";

cout<<"1. The file does not exist.\n";

cout<<"2. The path was not found.\n";

exit(1); // just exit

// 0-normal, non zero - some error

}

// if successful opening file for reading

else

{

cout<<"The "<<filename<<" file was opened successfully!\n";

cout<<"\nDo some file processing here...\n";

}

// close file for input

inputfile.close();

// test if fail to close the file

if(inputfile.fail())

{

cout<<"\nThe file "<<filename<<" could not be closed!\n";

exit(1);

}

// else

else

cout<<"\nThe "<<filename<<" file was closed successfully!\n";

}

// Provided the testfileio.txt file exists on the C: drive

 

Output example:

 

Enter the file name to be opened: C:\testfileio.txt

The C:\testfileio.txt file was opened successfully!

Do some file processing here...

The C:\testfileio.txt file was closed successfully!

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index