Arquivos C++
Arquivos C++
A fstream
biblioteca nos permite trabalhar com arquivos.
Para usar a fstream
biblioteca, inclua o padrão <iostream>
E o <fstream>
arquivo de cabeçalho:
Exemplo
#include <iostream>
#include <fstream>
Existem três classes incluídas na fstream
biblioteca, que são usadas para criar, escrever ou ler arquivos:
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 |
Criar e gravar em um arquivo
Para criar um arquivo, use a classe ofstream
ou fstream
e especifique o nome do arquivo.
Para gravar no arquivo, use o operador de inserção ( <<
).
Exemplo
#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 que fechamos o arquivo?
É considerado uma boa prática e pode limpar espaço de memória desnecessário.
Ler um arquivo
Para ler de um arquivo, use a classe ifstream
ou fstream
e o nome do arquivo.
Observe que também usamos um while
loop junto com a getline()
função (que pertence à ifstream
classe) para ler o arquivo linha por linha e imprimir o conteúdo do arquivo:
Exemplo
// 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();