Archivos C++
Archivos C++
La fstream
biblioteca nos permite trabajar con archivos.
Para usar la fstream
biblioteca, incluya tanto el archivo estándar como <iostream>
el de <fstream>
encabezado:
Ejemplo
#include <iostream>
#include <fstream>
Hay tres clases incluidas en la fstream
biblioteca, que se utilizan para crear, escribir o leer archivos:
Class | Description |
---|---|
ofstream |
Creates and writes to files |
ifstream |
Reads from files |
fstream |
A combination of ofstream and ifstream: creates, reads, and writes to files |
Crear y escribir en un archivo
Para crear un archivo, utilice la clase ofstream
o fstream
y especifique el nombre del archivo.
Para escribir en el archivo, utilice el operador de inserción ( <<
).
Ejemplo
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
//
Write to the file
MyFile << "Files can be tricky, but it is fun
enough!";
//
Close the file
MyFile.close();
}
¿Por qué cerramos el archivo?
Se considera una buena práctica y puede limpiar espacio de memoria innecesario.
leer un archivo
Para leer de un archivo, use la clase ifstream
o fstream
y el nombre del archivo.
Tenga en cuenta que también usamos un while
bucle junto con la getline()
función (que pertenece a la ifstream
clase) para leer el archivo línea por línea e imprimir el contenido del archivo:
Ejemplo
// Create a
text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while
loop together with the getline() function to read the file line by line
while (getline (MyReadFile,
myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();