Files · Archivos
| English | Español |
|---|---|
| file/faɪl/ | archivo |
| text file/tekst faɪl/ | archivo de texto |
| secondary storage/ˈsekəndəri ˈstɔːrɪdʒ/ | almacenamiento secundario |
| persistence/pəˈsɪstəns/ | persistencia |
| end of file/end ɒv faɪl/ | fin de archivo |
| separator/ˈsepəreɪtə/ | separador |
| sequential/siːˈkwenʃl/ | secuencial |
The game that remembered
- Until 1987, switching off a games console erased everything. Every session started from the first screen; a long game was a long afternoon or nothing.
- The Legend of Zelda shipped with a small battery inside the cartridge that kept a few hundred bytes alive. For the first time a home game could save, and pick up where you left off.
- Every high score, every document, every setting you have ever kept exists for the same reason: RAM forgets when the power goes, and a file 文件 does not.
- This lesson is why files exist and how pseudocode reads and writes a text file, line by line.
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.
Why files
- Variables live in RAM and disappear when the program ends. A file on secondary storage 辅助存储器 keeps data between program runs: persistence 持久性.
- Files let one program's output become another program's input, so data can be shared.
- A file can hold more than fits in memory, and a program can restart from a saved state.
The variable is gone at the end of the run; the file is still there tomorrow
¿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? · ¿Por qué un programa escribe datos en un archivo en lugar de mantenerlos en una variable?
RAM is volatile, so data is lost on exit. A file on secondary storage persists between runs. · La RAM es volátil, por lo que los datos se pierden al salir. Un archivo en almacenamiento secundario persiste entre ejecuciones.
Text files and the three modes
- A text file 文本文件 stores data as lines of characters, which a program reads and writes one line at a time, from the start. That sequence of lines is what lets a loop work through it.
OPENFILE … FOR READreads from the first line.FOR WRITEcreates a new file, or overwrites an existing one.FOR APPENDadds new lines at the end, keeping what is there.- Open before use, close after. A file has one mode at a time.
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. · Asocia cada modo de apertura de archivo con lo que hace.
READ reads; WRITE replaces from scratch; APPEND adds to the end without losing what is there. · LEER lee; ESCRIBIR reemplaza desde cero; ANEXAR añade al final sin perder lo que hay allí.
To add lines to the end of an existing file without losing its contents, open it FOR ____. · Para añadir líneas al final de un archivo existente sin perder su contenido, ábrelo PARA ____.
WRITE would start the file empty. APPEND keeps what is there and writes after it. · ESCRIBIR iniciaría el archivo vacío. ANEXAR mantiene lo que hay y escribe después.
Reading every line
EOFtests for the end of file 文件结束. Test it before each read: reading past the end is an error.CLOSEFILEmatters: buffered data may be lost and other programs locked out of a file left open.
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 · Manejo de un archivo: abrir → usar → cerrar
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. · Paso a paso el ciclo de vida que sigue cada archivo. Las dos partes fáciles de olvidar son verificar el final del archivo (EOF) al leer en un bucle, y siempre cerrar al final.
What does EOF test for? · ¿Qué prueba el EOF?
EOF (end of file) is checked before each read so the loop stops when there is no more data. · El EOF (final de archivo) se verifica antes de cada lectura para que el bucle se detenga cuando no haya más datos.
Why must you always close a file after using it? · ¿Por qué debes siempre cerrar un archivo después de usarlo?
Closing flushes buffered writes to disk and releases the lock so other programs can use the file. · Cerrar vacía los writes en búfer al disco y libera el bloqueo para que otros programas puedan usar el archivo.
Writing lines
WRITEstarts the file empty. To add to a log that must keep its history, open itFOR APPENDinstead.- A text file holds strings: a number is converted with
NUM_TO_STRon the way out.
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.
Worked example: the last three lines of a file
- Write a procedure
LastLines(FileName)that outputs the last three lines of a text file, in order.
- Each new line pushes the previous ones along, so at
EOFthe three variables hold the last three lines; a shorter file outputs empty strings. For the first five lines, count the reads and stop at five or atEOF, whichever comes first. An empty file makesEOFtrue immediately after opening.
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. · Ordena los pasos del procedimiento LastLines.
Initialise, open, loop with the shift before the read, close, output. Shifting after the read would lose the newest line. · Inicializa, abre, bucle con el desplazamiento antes de la lectura, cierra, imprime. Desplazar después de la lectura perdería la línea más nueva.
Fields in a line
- A record is written as one line, its fields joined by a separator 分隔符 character, and each number or Boolean converted with
NUM_TO_STR(and read back withSTR_TO_NUM, or by comparing with"TRUE"). - Choose a separator that can never appear in the data: a comma or
|for names and numbers; never a space when a name may contain one. - Reading back: read the line, split it at the separator, convert each field to its type, store it in the record.
Join with a separator to write; split and convert to read
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? · Una línea almacena el nombre completo y la puntuación de un jugador. ¿Cuál es la opción de separador más segura?
The separator must never occur inside a field. A full name contains a space, and a score contains digits. · El separador nunca debe ocurrir dentro de un campo. Un nombre completo contiene un espacio, y una puntuación contiene dígitos.
An INTEGER can be written to a text file directly, without converting it to a string first. · Un INTEGER puede escribirse directamente en un archivo de texto, sin convertirlo primero a cadena.
A text file holds lines of characters. Convert with NUM_TO_STR to write and STR_TO_NUM to read back. · Un archivo de texto contiene líneas de caracteres. Convierte con NUM_TO_STR para escribir y STR_TO_NUM para leer de nuevo.
Worked example: save a record, load it back
- A record
Playerhas fieldsName : STRINGandScore : INTEGER. Write pseudocode to append it toscores.txtas one line, and to read one line back into the record.
- The marks: the right mode, the conversion of the number in both directions, a separator that cannot occur in a name, and both files closed.
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 all · todos that apply. · Para almacenar un registro como una sola línea de un archivo de texto, un programa debe: seleccionar todos los que correspondan.
Convert, join, write, close. A text file has no binary layout; that is what a binary file would do. · Convierte, une, escribe, cierra. Un archivo de texto no tiene disposición binaria; eso es lo que haría un archivo binario.
Serial and direct access
- A text file is serial 顺序 (sequential): it is read in order from the start, so finding one line means reading every line before it.
- Direct (random) access jumps straight to a record at a calculated position without reading the others; it needs fixed-length records, which text files do not have.
- For the syllabus, the text-file loop above is the model: open, test
EOF, read, close.
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. · El acceso directo (aleatorio) permite que un programa salte directamente a un registro sin leer los otros primero.
Serial access must read from the start. · El acceso serial debe leer desde el inicio.
Marks that slip away
- Reading past the end. Test
EOFbefore everyREADFILE. - Opening
FOR WRITEwhen the file must keep its contents. That isAPPEND. - Writing a number without
NUM_TO_STR, or reading it back withoutSTR_TO_NUM. A text file holds strings. - Forgetting
CLOSEFILE, or using a file beforeOPENFILE. Both lose the mark for the file handling.
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.
You've got it
- files give persistence: data survives the end of the program, can be shared, and can exceed memory
OPENFILE … FOR READ | WRITE | APPEND→READFILE/WRITEFILE→CLOSEFILE;WRITEoverwrites,APPENDadds at the end- test
EOFbefore each read; convert numbers withNUM_TO_STRout andSTR_TO_NUMback - one record = one line, fields joined by a separator that never appears in the data
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