Group
File Management in C++
Objective
1. Include the necessary headers to handle file input.
2. Prompt the user to enter the name of the file to be read.
3. Use an ifstream object to open and read the file line by line.
4. Display each line of the file on the console.
5. Handle the case where the file cannot be opened.
Write a program that reads a text file and prints it to the console.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for standard input and output
#include <fstream> // Include for file stream operations
#include <string> // Include for using the string class
using namespace std;
int main() {
string filename; // Variable to store the file name
string line; // Variable to store each line from the file
// Prompt the user to enter the file name
cout << "Enter the name of the file to read: ";
cin >> filename; // Read the file name from the user
ifstream inputFile(filename); // Create an input file stream and open the file
// Check if the file was successfully opened
if (inputFile.is_open()) {
cout << "Contents of the file:" << endl;
// Read the file line by line and print each line
while (getline(inputFile, line)) {
cout << line << endl; // Print the current line
}
inputFile.close(); // Close the file after reading
} else {
// If the file could not be opened, display an error message
cout << "Error: Could not open the file." << endl;
}
return 0; // End of the program
}
Output
Enter the name of the file to read: sample.txt
Contents of the file:
This is a sample text file.
It contains multiple lines.
Each line is displayed in the console.