Text files: write then read · Arquivos de texto: escrever depois ler
Files keep data after the program ends
- A file stores data on disk, so it is still there after your program stops.
- You work with a file through a
FILE *— a pointer you get fromfopen. - In these tasks you write a file, then read it back in the same program, so everything is self-contained.
Arquivos mantêm dados depois que o programa termina
- Um arquivo armazena dados em disco, então continua lá depois que seu programa para.
- Você trabalha com um arquivo por meio de um
FILE *— um ponteiro obtido defopen. - Nestas tarefas você escreve um arquivo, depois lê de volta no mesmo programa, então tudo é autônomo.
Writing then reading a file · Escrevendo depois lendo um arquivo
A file is used in three steps: open · abrir it with fopen, read or write, then close · fechar it with fclose. · Um arquivo é usado em três passos: abra-o com fopen, leia ou escreva, depois feche-o com fclose.
Opening and closing
fopen("data.txt", "w")opens a file for writing (it creates or empties the file).fopen("data.txt", "r")opens it for reading.- Always
fclose(f)when you are done, so the data is saved and the file is released.
Abrindo e fechando
fopen("data.txt", "w")abre um arquivo para escrita (cria ou esvazia o arquivo).fopen("data.txt", "r")abre-o para leitura.- Sempre
fclose(f)quando terminar, para salvar os dados e liberar o arquivo.
Writing with fprintf
fprintfworks likeprintf, but its first argument is theFILE *.fprintf(f, "%d\n", x);writes the numberxand a newline into the filef.- Write each value on its own line so it is easy to read back.
Escrevendo com fprintf
fprintffunciona comoprintf, mas seu primeiro argumento é oFILE *.fprintf(f, "%d\n", x);escreve o númeroxe uma nova linha no arquivof.- Escreva cada valor em sua própria linha para facilitar a leitura posterior.
Reading with fscanf and fgets
fscanf(f, "%d", &x)reads one number; it returns1when it succeeds.fgets(buf, size, f)reads one line of text intobuf; it returnsNULLat the end.- Loop until the read fails to process the whole file.
Lendo com fscanf e fgets
fscanf(f, "%d", &x)lê um número; retorna1quando tem sucesso.fgets(buf, size, f)lê uma linha de texto embuf; retornaNULLno final.- Faça loop até a leitura falhar para processar todo o arquivo.
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
fprintf(f, "3\n4\n");
fclose(f);
f = fopen("nums.txt", "r");
int x, total = 0;
while (fscanf(f, "%d", &x) == 1) {
total += x;
}
fclose(f);
printf("%d\n", total); // 7
return 0;
}
Common mistakes
- Check that
fopendid not returnNULLbefore reading or writing. - Always
fclosethe file when you are done.
Erros comuns
- Verifique se
fopennão retornouNULLantes de ler ou escrever. - Sempre
fcloseo arquivo quando terminar.
Now you try
- These tasks are full programs: write inside
main, and Check answer tests the output. - Write the file first,
fcloseit, then open it again for reading and loop until the read fails.
Agora você tenta
- Estas tarefas são programas completos: escreva dentro de
main, e Check answer testa a saída. - Escreva o arquivo primeiro,
fclose, depois abra novamente para leitura e faça loop até a leitura falhar.
In main: write the numbers 10, 20, 5, 7 (one per line) to a file, close it, then open it again and add them up with fscanf. Print the total (42). · Em main: escreva os números 10, 20, 5, 7 (um por linha) em um arquivo, feche-o, abra-o novamente e some-os com fscanf. Imprima o total (42).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
In main: write three lines of text to a file, close it, then open it again and count the lines with fgets. Print the count (3). · Em main: escreva três linhas de texto em um arquivo, feche-o, abra-o novamente e conte as linhas com fgets. Imprima a contagem (3).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.