Archivos
Introducido
17:29
Tipos y estructuras de datos
Cada valor que guarda tu programa necesita un tipo de dato —y elegir el correcto importa. Digamos que guardas si un artículo está en stock. Podrías escribir la palabra sí…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| games console | A device that runs video games and connects to a screen. |
| cartridge | A removable device that stores a game for a games console. |
| bytes | Units of eight bits used to store data in a computer. |
| save/seɪv/ | To store data so that it can be used later. |
| document/ˈdɒkjuːmənt/ | A file containing information created or edited by a user. |
| RAM/ræm/ | Random-access memory used for working data and instructions, usually losing its contents when power is removed. |
| file/faɪl/ | archivo |
| pseudocode/ˈsuːdəʊkəʊd/ | A language-independent description of an algorithm using structured, programming-like statements. |
| text file/tekst faɪl/ | archivo de texto |
| Variables/ˈveərɪəblz/ | A quantity or named value that can change or take different values. |
| secondary storage/ˈsekəndəri ˈstɔːrɪdʒ/ | almacenamiento secundario |
| persistence/pəˈsɪstəns/ | persistencia |
| memory/ˈmeməri/ | The part of a computer that holds data and programs currently in use. |
| mode/məʊd/ | A setting that determines how a file is opened or used, such as reading, writing or appending. |
| characters/ˈkærɪktəz/ | A text unit such as a letter, digit, punctuation mark or other symbol. |
| loop/luːp/ | A structure that repeats a sequence of instructions. |
| overwrites | Replaces the existing contents of a file with new data. |
| end of file/end ɒv faɪl/ | fin de archivo |
| buffered data | Data held temporarily in memory before it is written to a file. |
| strings/strɪŋz/ | Sequences of characters used as text in a program. |
| procedure/prəˈsiːdʒə/ | A named sequence of instructions that performs a task when called. |
| empty strings | Text values that contain no characters at all. |
| fields/fiːldz/ | Parts of a database record that each hold one item of data. |
| record/ˈrekɔːd/ | A stored collection of information about an item, person or event. |
| separator/ˈsepəreɪtə/ | separador |
| Boolean/ˈbuːlɪən/ | A logical value that is either true or false. |
| escaping scheme | A set of rules for writing special characters so they are read correctly. |
| type/taɪp/ | A category of data that determines what values it can hold. |
| serial/ˈsɪərɪəl/ | Describes access to data in order, starting at the beginning of a file. |
| sequential/siːˈkwenʃl/ | secuencial |
| Direct (random) access | A way to reach a record at a calculated position without reading earlier records. |
| fixed-length records | Records that all take up the same amount of storage space. |
El juego que recordó
- Hasta 1987, apagar una consola de videojuegos borraba todo. Cada sesión comenzaba desde la primera pantalla; un juego largo era una larga tarde o nada.
- The Legend of Zelda se enviaba con una pequeña batería dentro del cartucho que mantenía unos pocos cientos de bytes activos. Por primera vez, un juego doméstico podía guardar y continuar donde lo dejó.
- Cada puntuación alta, cada documento, cada configuración que hayas guardado alguna vez existe por la misma razón: la RAM olvida cuando se corta la corriente, y un archivo no.
- Esta lección explica por qué existen los archivos y cómo pseudocódigo lee y escribe un archivo de texto, línea por línea.
¿Por qué archivos
- Las variables viven en la RAM y desaparecen cuando termina el programa. Un archivo en almacenamiento secundario mantiene los datos entre ejecuciones del programa: persistencia.
- Los archivos permiten que la salida de un programa sea la entrada de otro, para que los datos puedan ser compartidos.
- Un archivo puede contener más de lo que cabe en la memoria, y un programa puede reiniciarse desde un estado guardado.

La variable se va al final de la ejecución; el archivo sigue ahí mañana
Why does a program write data to a file rather than keeping it in a variable?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
RAM is volatile, so data is lost on exit. A file on secondary storage persists between runs.
Archivos de texto y los tres modos
- Un archivo de texto almacena datos como líneas de caracteres, que un programa lee y escribe una línea a la vez, desde el principio. Esa secuencia de líneas es lo que permite que un bucle las recorra.
OPENFILE … FOR READlee desde la primera línea.FOR WRITEcrea un nuevo archivo o sobrescribe uno existente.FOR APPENDañade nuevas líneas al final, conservando lo que ya está.- Abrir antes de usar, cerrar después. Un archivo tiene un modo a la vez.

Match each file-open mode to what it does.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
READ reads; WRITE replaces from scratch; APPEND adds to the end without losing what is there.
To add lines to the end of an existing file without losing its contents, open it FOR ____.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
WRITE would start the file empty. APPEND keeps what is there and writes after it.
Leer cada línea
OPENFILE "data.txt" FOR READ
WHILE NOT EOF("data.txt") DO
READFILE "data.txt", LineString
OUTPUT LineString
ENDWHILE
CLOSEFILE "data.txt"
EOFcomprueba si se ha alcanzado el final del archivo. Pruébalo antes de cada lectura: leer más allá del final es un error.CLOSEFILEes importante: los datos en búfer pueden perderse y otros programas quedarán bloqueados si se deja un archivo abierto.
Handling a file: open → use → close
Step through the lifecycle every file follows. The two easy-to-forget parts are testing EOF while reading in a loop, and always closing at the end.
What does EOF test for?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
EOF (end of file) is checked before each read so the loop stops when there is no more data.
Why must you always close a file after using it?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Closing flushes buffered writes to disk and releases the lock so other programs can use the file.
Escribir líneas
OPENFILE "log.txt" FOR WRITE
FOR i ← 1 TO 100
WRITEFILE "log.txt", "Event " & NUM_TO_STR(i)
NEXT i
CLOSEFILE "log.txt"
WRITEinicia el archivo vacío. Para añadir a un registro que debe conservar su historial, ábreloFOR APPENDen su lugar.- Un archivo de texto contiene cadenas: un número se convierte con
NUM_TO_STRal salir.
Ejemplo resuelto: las últimas tres líneas de un archivo
- Escribe un procedimiento
LastLines(FileName)que muestre las últimas tres líneas de un archivo de texto, en orden.
PROCEDURE LastLines(BYVAL FileName : STRING)
DECLARE LineX, LineY, LineZ : STRING
LineX ← ""
LineY ← ""
LineZ ← ""
OPENFILE FileName FOR READ
WHILE NOT EOF(FileName) DO
LineX ← LineY
LineY ← LineZ
READFILE FileName, LineZ
ENDWHILE
CLOSEFILE FileName
OUTPUT LineX
OUTPUT LineY
OUTPUT LineZ
ENDPROCEDURE
- Cada nueva línea desplaza las anteriores, por lo que al alcanzar
EOFlas tres variables contienen las últimas tres líneas; un archivo más corto muestra cadenas vacías. Para las cinco primeras líneas, cuenta las lecturas y detente en cinco o enEOF, lo que ocurra primero. Un archivo vacío hace queEOFsea verdadero inmediatamente después de abrirlo.

Put the steps of the LastLines procedure in order.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Initialise, open, loop with the shift before the read, close, output. Shifting after the read would lose the newest line.
Campos en una línea
- Un registro se escribe como una línea, con sus campos unidos por un carácter separador, y cada número o Booleano convertido con
NUM_TO_STR(y leído de nuevo conSTR_TO_NUM, o comparando con"TRUE"). - Elige un separador que nunca aparezca en los datos: una coma o
|para nombres y números; nunca un espacio si un nombre puede contener uno. - Leer de nuevo: lee la línea, divídela en el separador, convierte cada campo a su tipo, guárdalo en el registro.

Únelos con un separador para escribir; divídelos y conviértelos para leer
A line stores a player's full name and score. Which separator is the safest choice?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The separator must never occur inside a field. A full name contains a space, and a score contains digits.
An INTEGER can be written to a text file directly, without converting it to a string first.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
A text file holds lines of characters. Convert with NUM_TO_STR to write and STR_TO_NUM to read back.
Ejemplo resuelto: guardar un registro, cargarlo de nuevo
- Un registro
Playertiene camposName : STRINGyScore : INTEGER. Escribe pseudocódigo para agregarlo ascores.txtcomo una línea, y para leer una línea de vuelta al registro.
OPENFILE "scores.txt" FOR APPEND
WRITEFILE "scores.txt", Player.Name & "," & NUM_TO_STR(Player.Score)
CLOSEFILE "scores.txt"
OPENFILE "scores.txt" FOR READ
READFILE "scores.txt", Line
Pos ← POSITION(Line, ",")
Player.Name ← LEFT(Line, Pos - 1)
Player.Score ← STR_TO_NUM(MID(Line, Pos + 1, LENGTH(Line) - Pos))
CLOSEFILE "scores.txt"
- Las calificaciones: el modo correcto, la conversión del número en ambas direcciones, un separador que no pueda ocurrir en un nombre, y ambos archivos cerrados.

To store a record as one line of a text file, a program must: select todos that apply.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Convert, join, write, close. A text file has no binary layout; that is what a binary file would do.
Acceso serial y directo
- Un archivo de texto es serial (secuencial): se lee en orden desde el principio, por lo que encontrar una línea significa leer todas las anteriores.
- El acceso directo (aleatorio) salta directamente a un registro en una posición calculada sin leer los demás; necesita registros de longitud fija, cosa que los archivos de texto no tienen.
- Para el programa de estudios, el bucle de archivo de texto anterior es el modelo: abrir, probar
EOF, leer, cerrar.

Direct (random) access lets a program jump straight to a record without reading the others first.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Serial access must read from the start.
Calificaciones que se pierden
- Leer más allá del final. Prueba
EOFantes de cadaREADFILE. - Abrir
FOR WRITEcuando el archivo debe mantener su contenido. Eso esAPPEND. - Escribir un número sin
NUM_TO_STR, o leerlo de nuevo sinSTR_TO_NUM. Un archivo de texto contiene cadenas. - Olvidar
CLOSEFILE, o usar un archivo antes deOPENFILE. Ambos hacen perder la calificación por manejo de archivos.
Lo has logrado
- Los archivos dan persistencia: los datos sobreviven al fin del programa, pueden compartirse y pueden superar la memoria
OPENFILE … FOR READ | WRITE | APPEND→READFILE/WRITEFILE→CLOSEFILE;WRITEsobrescribe,APPENDañade al final- prueba
EOFantes de cada lectura; convierte números conNUM_TO_STRal salir ySTR_TO_NUMal volver - un registro = una línea, campos unidos por un separador que nunca aparece en los datos
¿Qué salió mal? Solo el equipo del sitio ve esta información.