Given the following, write a code SEGMENT that does the following: Creates a string variable to store a file name (to be entered by the user) Requests the input file name from the user and stores the name in a variable Opens the input file using the entered file name Tests the STATE of the file open. If the file does not open, output a message to the user exit the program Be sure to: Include the necessary header files Declare necessary variables
-
- Given the following, write a code SEGMENT that does the following:
- Creates a string variable to store a file name (to be entered by the user)
- Requests the input file name from the user and stores the name in a variable
- Opens the input file using the entered file name
- Tests the STATE of the file open. If the file does not open, output a message to the user exit the
program
Be sure to:
- Include the necessary header files
- Declare necessary variables
Note:
Programming language is missing in the question. So we will answer this program in C++ language. If you want this program to be executed in some other programming language, kindly resubmit the question with a specific programming language.
Program:
A required program in C++ language is as follows,
//Include necessary header files
#include<iostream>
#include<fstream>
using namespace std;
int main(){
//Declare a string variable
string filename;
ifstream infile;
//Requests the input file name from the user
cout<<"Please enter input file name: ";
// Store the file name in a string variable "filename"
getline(cin,filename);
infile.open(filename.c_str());
//Tests the STATE of the file open
if(infile.fail())
cout<<"File cannot be opened!"<<endl;
else
cout <<"File opened successfully!"<<endl;
//Close the file and exit
infile.close();
return 0;
}
Step by step
Solved in 3 steps with 4 images