PRO
Parth
asked

Expert
Kelish Rai answered
To open a file by asking the user for the filename, you simply take their input before attempting to open the file. Here's how you can do it:
#include
#include
using namespace std;
int main() {
string filename;
cout << "Enter the filename: ";
cin >> filename;
// Create an fstream object
fstream fs;
// Open the file in read mode
fs.open(filename);
// Check if the file was opened successfully
if (!fs) {
cout << "Could not open the file." << endl;
return 1;
}
return 0;
} Output
Enter the filename: myfile.txt
File opened successfully.In the code:
cin >> filename;takes the filename input from the user.fs.open(filename);attempts to open the file.We check
if (!fs)to confirm if the file opened correctly. If it fails, we print an error message and exit the program.At the end, we safely close the file using
fs.close();, which is a good practice even if the program ends immediately after.
Note: If the filename contains spaces (like "my file.txt"), cin >> filename; will not work properly because cin stops reading at the first space. In that case, you should use getline(cin, filename); instead.
C++
This question was asked as part of the Learn C++ Intermediate course.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer