File processing · Procesamiento de archivos
| English | Español |
|---|---|
| overwrite/ˌəʊvəˈraɪt/ | sobreescribir |
| APPEND/əˈpend/ | ANEXAR |
| temporary file/ˈtemprəri faɪl/ | archivo temporal |
You cannot change one line of a text file
- A program must correct a spelling in the middle of a customer file. It seems obvious: find the line, change it, save.
- Almost no language will let you. A text file is a stream of characters, and the corrected name is a different length from the old one, so every byte after it would have to move.
- So the standard answer is not to edit at all: copy the whole file, changing that one line as it passes, and put the copy in place of the original.
- This lesson is the file operations, that copy-through pattern for updating, and the pitfalls that cause real bugs.
The operations
OPENFILE name FOR READ | WRITE | APPENDopens the file. READ opens an existing file at the start; WRITE creates it, or overwrites 覆盖 an existing one; APPEND 追加 opens it and adds at the end.READFILE name, variablereads the next line.WRITEFILE name, valuewrites one.CLOSEFILE namecloses it.EOF(name)is TRUE when the end has been reached.- Choose the file layout and access method first: serial, sequential and random files serve different operations. The copy-through examples here use sequential access to text records.
- The pattern for reading a whole file is always the same:
OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt") DO
READFILE "names.txt", thisName
OUTPUT thisName
ENDWHILE
CLOSEFILE "names.txt"

Open, use, close, every time
File access route · Ruta de acceso a archivos
Follow a file from storage to program and back safely. · Siga un archivo desde el almacenamiento hasta el programa y de vuelta de forma segura.
What does opening a file FOR WRITE do to existing contents? · ¿Qué hace abrir un archivo PARA ESCRIBIR con respecto al contenido existente?
WRITE creates or overwrites the file. To keep existing contents and add more, use APPEND. · WRITE crea o sobrescribe el archivo. Para mantener el contenido existente y agregar más, use APPEND.
Match each file operation to what it does. · Asocie cada operación de archivo con lo que hace.
WRITE overwrites, APPEND adds; EOF marks the end; the search loop stops early once the value is found. · WRITE sobrescribe, APPEND agrega; EOF marca el final; el bucle de búsqueda se detiene tempranamente una vez encontrado el valor.
Searching a file
- To search, read line by line and stop when the target is found. Two conditions are needed:
WHILE NOT EOF(…) AND NOT found. - The · El
foundflag matters. Without it the loop reads the whole file even after a match, which is wasteful, and there is nothing to test afterwards to report "not found".
found ← FALSE
OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt") AND NOT found DO
READFILE "names.txt", thisName
IF thisName = target THEN
found ← TRUE
ENDIF
ENDWHILE
CLOSEFILE "names.txt"
When searching a file for a value, the loop condition usually includes: · Al buscar un valor en un archivo, la condición del bucle generalmente incluye:
Stopping when found avoids reading the rest of the file unnecessarily. · Detenerse cuando se encuentra evita leer el resto del archivo innecesariamente.
Why does a file search loop use WHILE NOT EOF AND NOT found? Select all · todos that apply. · ¿Por qué un bucle de búsqueda de archivos usa WHILE NOT EOF AND NOT found? Seleccione todas las que correspondan.
Every file must still be closed. The two conditions handle early exit and the end of the file respectively. · Cada archivo debe cerrarse aún. Las dos condiciones manejan respectivamente la salida anticipada y el final del archivo.
Updating: the temporary-file pattern
- Because a text file cannot be edited in place, updating uses a temporary file 临时文件.
- Open the original FOR READ and a temporary file FOR WRITE. Read each line in turn; write it to the temporary file either changed or unchanged.
- Close both files, then replace the original with the temporary file.
- The same pattern does everything: to delete a record, skip writing that line; to insert one, write the new line at the right point as you copy.
To update a text file when in-place editing is not possible, you: · Para actualizar un archivo de texto cuando no es posible la edición in situ, usted:
Copy each line (changed or not) to a temp file, then swap it in for the original. · Copie cada línea (cambiada o no) a un archivo temporal, luego intercámbielo por el original.
Put the steps of deleting one record from a text file in order. · Coloque los pasos para eliminar un registro de un archivo de texto en orden.
The last step is the one candidates leave out, and without it nothing has changed. The same pattern inserts or edits a record. · El último paso es el que los candidatos suelen omitir, y sin él nada cambia. El mismo patrón inserta o edita un registro.
Worked example: delete a record
- Describe how a program deletes one record from a text file. [4]
- Open the original file for reading and a temporary file for writing.
- Read each line in turn. If the line is not · no the one to delete, write it to the temporary file; if it is, do not write it.
- When the end of the original is reached, close both files.
- Replace the original file with the temporary file. All four steps score, and the last one is the one candidates forget.
A program writes 500 records then ends without closing the file, and the last few are missing. Why? · Un programa escribe 500 registros y termina sin cerrar el archivo, y faltan los últimos pocos. ¿Por qué?
Writes are buffered for speed. Closing the file flushes the buffer, and it may also release a lock other programs are waiting on. · Las escrituras están en buffer por velocidad. Cerrar el archivo vacía el buffer, y también puede liberar un bloqueo que otros programas esperan.
The pitfalls
- Forgetting to close a file: buffered data may never be written, so the last records vanish, and the file may stay locked against other programs.
- Opening · Apertura FOR WRITE when APPEND was meant: the entire existing contents are destroyed the instant the file is opened, before a single line is written.
- Reading past EOF: test
EOFbefore every read, not after. - Hard-coded paths: put the filename in a constant so it appears once and the program can be moved.
Forgetting to close a file can lose buffered writes and lock other programs out — so you should always close a file when finished. · Olvidar cerrar un archivo puede perder escrituras en buffer y bloquear a otros programas, así que siempre debe cerrar un archivo cuando termine.
Closing flushes buffered data to disk and releases the lock — a FINALLY block is a good place to guarantee it. · Cerrar vacía los datos en buffer al disco y libera el bloqueo: un bloque FINALLY es un buen lugar para garantizarlo.
To add today's entries to a log that must keep its history, open the file FOR ____. · Para agregar las entradas de hoy a un registro que debe mantener su historial, abra el archivo FOR ____.
WRITE would destroy every previous entry the instant the file was opened, before a single line was written. · WRITE destruiría todas las entradas anteriores en el instante en que se abre el archivo, antes de escribir una sola línea.
Worked example: which mode
- A program adds today's transactions to a running log that must keep its history. APPEND: WRITE would destroy every previous entry.
- A program produces a fresh report each night, replacing yesterday's. WRITE: creating or overwriting is exactly what is wanted.
- A program reads a configuration file at start-up. READ.
- The mode is chosen by what must happen to the existing contents: kept and added to, destroyed, or left alone.
Marks that slip away
- The update pattern ends by replacing the original with the temporary file. Copying without that final step changes nothing.
- A search loop needs both · ambas conditions,
NOT EOFand · y NOT found, and something to test afterwards. - WRITE overwrites; APPEND adds. Choosing wrongly destroys the file at the moment of opening.
- Always
CLOSEFILE. Say why: buffered data may be lost otherwise.
You've got it
OPENFILE … FOR READ | WRITE | APPEND, thenREADFILEorWRITEFILE, thenCLOSEFILE;EOFis tested before · antes each read- WRITE creates or overwrites, APPEND keeps the contents and adds at the end, READ starts at the beginning
- search with
WHILE NOT EOF AND NOT found, so the loop stops early and "not found" can be reported - update by copying through a temporary file, writing each line changed or unchanged, skipping a line to delete or adding one to insert, then replacing the original