File processing · Processamento de arquivos
| English | Português |
|---|---|
| overwrite/ˌəʊvəˈraɪt/ | sobrescrever |
| APPEND/əˈpend/ | APPEND |
| temporary file/ˈtemprəri faɪl/ | arquivo temporário |
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 · Rota de acesso a arquivo
Follow a file from storage to program and back safely. · Siga um arquivo do armazenamento ao programa e de volta com segurança.
What does opening a file FOR WRITE do to existing contents? · O que abrir um arquivo PARA ESCRITA faz com o conteúdo existente?
WRITE creates or overwrites the file. To keep existing contents and add more, use APPEND. · WRITE cria ou sobrescreve o arquivo. Para manter conteúdo existente e adicionar mais, use APPEND.
Match each file operation to what it does. · Combine cada operação de arquivo com o que ela faz.
WRITE overwrites, APPEND adds; EOF marks the end; the search loop stops early once the value is found. · ESCREVER sobrescreve, ANEXAR adiciona; FIM DO ARQUIVO marca o final; o loop de busca para cedo assim que o valor é encontrado.
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 · A
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: · Ao buscar um valor em um arquivo, a condição do loop geralmente inclui:
Stopping when found avoids reading the rest of the file unnecessarily. · Parar ao encontrar evita ler o restante do arquivo desnecessariamente.
Why does a file search loop use WHILE NOT EOF AND NOT found? Select all · todos that apply. · Por que um loop de busca em arquivo usa ENQUANTO NÃO FIM DO ARQUIVO E NÃO encontrado? Selecione todos os que se aplicam.
Every file must still be closed. The two conditions handle early exit and the end of the file respectively. · Todo arquivo ainda deve ser fechado. As duas condições tratam a saída antecipada e o fim do arquivo, respectivamente.
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 · inserir 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 atualizar um arquivo de texto quando a edição in-place não é possível, você:
Copy each line (changed or not) to a temp file, then swap it in for the original. · Copia cada linha (alterada ou não) para um arquivo temporário, depois a insere no lugar do original.
Put the steps of deleting one record from a text file in order. · Coloque as etapas para excluir um registro de um arquivo de texto em ordem.
The last step is the one candidates leave out, and without it nothing has changed. The same pattern inserts or edits a record. · A última etapa é a que os candidatos costumam omitir, e sem ela nada muda. O mesmo padrão insere ou edita um 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 · não 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? · Um programa grava 500 registros e termina sem fechar o arquivo, e os últimos alguns estão faltando. 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. · Escritas são bufferadas para velocidade. Fechar o arquivo limpa o buffer, e pode também liberar um bloqueio que outros programas aguardam.
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 · Abertura 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. · Esquecer de fechar um arquivo pode perder escritas em buffer e bloquear outros programas — então você deve sempre fechar um arquivo ao terminar.
Closing flushes buffered data to disk and releases the lock — a FINALLY block is a good place to guarantee it. · Fechar limpa os dados em buffer para o disco e libera o bloqueio — um bloco FINALLY é um bom lugar para garantir isso.
To add today's entries to a log that must keep its history, open the file FOR ____. · Para adicionar as entradas de hoje a um log que deve manter seu histórico, abra o arquivo PARA ____.
WRITE would destroy every previous entry the instant the file was opened, before a single line was written. · ESCREVER destruiria todas as entradas anteriores no instante em que o arquivo fosse aberto, antes de qualquer linha ser escrita.
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 · ambos conditions,
NOT EOFand · e 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, thenREADFILEor · ou WRITEFILE, 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