Grupo
Manejo de Archivos en C++
Ojetivo
1. Incluir los encabezados necesarios para gestionar la entrada de archivos.
2. Solicitar al usuario que introduzca el nombre del archivo que se va a leer.
3. Usar un objeto ifstream para abrir y leer el archivo línea por línea.
4. Mostrar cada línea del archivo en la consola.
5. Gestionar el caso en que el archivo no se pueda abrir.
Escribir un programa que lea un archivo de texto y lo imprima en la consola.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
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.
Comparte este ejercicio C++