¿Cómo leer de un archivo en C++?
En C++, el manejo de archivos permite a los usuarios leer, escribir y actualizar datos en un archivo externo. En este artículo, aprenderemos cómo leer algunos datos de un archivo en C++.
Leer desde un archivo en C++
Para leer el contenido de un archivo en C++, podemos usar el std::ifstream> (flujo de archivo de entrada) para crear el flujo de entrada al archivo. Luego podemos usar la función std::getline() para leer los datos de este archivo y almacenarlos en algún objeto de cadena local.
Acercarse
- Primero, abra el archivo usando std::
ifstream inputFile('filePath').>Then, c>Compruebe si el archivo se abrió correctamente o no se utiliza.is_open()>que regresafalse if>el archivo no se pudo abrir y de lo contrario es verdadero.- Leer el archivo línea por línea
using>std:: getline()>function and print the content.>Finally, close the file using>std::fstream::close()>.>
Programa C++ para leer desde un archivo
El siguiente ejemplo demuestra cómo podemos abrir y leer el contenido de un archivo llamado input.txt en C++.
C++
// C++ program to read from a file> #include> #include> #include> using> namespace> std;> > int> main()> {> > // Open the input file named 'input.txt'> > ifstream inputFile(> 'input.txt'> );> > > // Check if the file is successfully opened> > if> (!inputFile.is_open()) {> > cerr < <> 'Error opening the file!'> < < endl;> > return> 1;> > }> > > string line;> // Declare a string variable to store each> > // line of the file> > > // Read each line of the file and print it to the> > // standard output stream> > cout < <> 'File Content: '> < < endl;> > while> (getline(inputFile, line)) {> > cout < < line < < endl;> // Print the current line> > }> > > // Close the file> > inputFile.close();> > > return> 0;> }> |
Producción
File Content: Hey Geek! Welcome to GfG. Happy Coding.
Complejidad del tiempo: O (n), donde n es el número de caracteres a leer.
Complejidad espacial: O (n)