Text files: write then read · Archivos de texto: escribir y luego leer
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.
Los archivos mantienen los datos después de que termina el programa
- Un archivo almacena datos en disco, por lo que siguen existiendo una vez que su programa ha terminado.
- Trabaja con un archivo a través de un
FILE *—un puntero que obtiene defopen.— - En estas tareas escribe un archivo y luego lo lee de nuevo dentro del mismo programa, para que todo quede autocontenido.
Writing then reading a file · Escribir y luego leer un archivo
A file is used in three steps: open · abrir it with fopen, read or write, then close · cerrar it with fclose. · Un archivo se utiliza en tres pasos: abrirlo con fopen, leer o escribir, luego cerrarlo con 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.
Apertura y cierre
fopen("data.txt", "w")abre un archivo para escribir (crea el archivo o lo vacía).fopen("data.txt", "r")lo abre para leer.- Utilice siempre
fclose(f)cuando haya terminado, para guardar los datos y liberar el archivo.
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.
Escritura con fprintf
fprintffunciona igual queprintf, pero su primer argumento es elFILE *.fprintf(f, "%d\n", x);escribe el númeroxseguido de un salto de línea en el archivof.- Escriba cada valor en una línea propia para facilitar su lectura 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.
Lectura con fscanf y fgets
fscanf(f, "%d", &x)lee un número; devuelve1cuando tiene éxito.fgets(buf, size, f)lee una línea de texto haciabuf; devuelveNULLal final del archivo.- Itere hasta que la lectura falle para procesar todo el archivo.
#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.
Errores comunes
- Verifique que
fopenno devolvióNULLantes de leer o escribir. - Cierre siempre el archivo con
fclosecuando haya terminado.
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.
Ahora practique
- Estas tareas son programas completos: escriba dentro de
main, y Comprobar respuesta verifica la salida. - Escriba primero el archivo, ciérrelo con
fclose, vuelva a abrirlo para leer e itere hasta que la lectura falle.
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). · En main: escribe los números 10, 20, 5, 7 (uno por línea) en un archivo, ciérralo, luego ábrelo nuevamente y súmalos con fscanf. Imprime el total (42).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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). · En main: escribe tres líneas de texto en un archivo, ciérralo, luego ábrelo nuevamente y cuenta las líneas con fgets. Imprime el conteo (3).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.