Files · Arquivos
| English | Português |
|---|---|
| file/faɪl/ | arquivo |
| text file/tekst faɪl/ | arquivo de texto |
| secondary storage/ˈsekəndəri ˈstɔːrɪdʒ/ | armazenamento secundário |
| persistence/pəˈsɪstəns/ | persistência |
| end of file/end ɒv faɪl/ | fim de arquivo |
| separator/ˈsepəreɪtə/ | separador |
| sequential/siːˈkwenʃl/ | sequencial |
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.
O jogo que se lembrava
- Até 1987, desligar um console apagava tudo. Cada sessão começava na primeira tela; um jogo longo era uma tarde longa ou nada.
- The Legend of Zelda veio com uma pequena bateria dentro do cartucho que mantinha alguns bytes vivos. Pela primeira vez um jogo caseiro podia salvar e retomar onde você parou.
- Cada pontuação máxima, cada documento, cada configuração que você já guardou existe pela mesma razão: RAM esquece quando a energia vai, e um arquivo 文件 não.
- Esta lição é por que arquivos existem e como pseudocódigo lê e escreve um arquivo de texto, linha por linha.
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 que arquivos
- Variáveis vivem na RAM e desaparecem quando o programa acaba. Um arquivo em armazenamento secundário 辅助存储器 mantém dados entre execuções de programas: persistência 持久性.
- Arquivos permitem que a saída de um programa seja a entrada de outro, para que os dados possam ser compartilhados.
- Um arquivo pode conter mais do que cabe na memória, e um programa pode reiniciar a partir de um estado salvo.

A variável foi embora no fim da execução; o arquivo ainda está lá amanhã
Why does a program write data to a file rather than keeping it in a variable? · Por que um programa escreve dados em um arquivo em vez de mantê-los em uma variável?
RAM is volatile, so data is lost on exit. A file on secondary storage persists between runs. · RAM é volátil, então os dados são perdidos na saída. Um arquivo em armazenamento secundário persiste entre execuções.
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.
Arquivos de texto e os três modos
- Um arquivo de texto 文本文件 armazena dados como linhas de caracteres, que um programa lê e escreve uma linha de cada vez, do início. Essa sequência de linhas é o que permite que um loop processe o conteúdo.
OPENFILE … FOR READlê da primeira linha.FOR WRITEcria um novo arquivo, ou sobrescreve um existente.FOR APPENDadiciona novas linhas no fim, mantendo o que há.- Abra antes de usar, feche depois. Um arquivo tem apenas um modo por vez.
Match each file-open mode to what it does. · Correlacione cada modo de abertura de arquivo com o que ele faz.
READ reads; WRITE replaces from scratch; APPEND adds to the end without losing what is there. · READ lê; WRITE substitui do zero; APPEND adiciona ao final sem perder o que está lá.
To add lines to the end of an existing file without losing its contents, open it FOR ____. · Para adicionar linhas ao final de um arquivo existente sem perder seu conteúdo, abra-o FOR ____.
WRITE would start the file empty. APPEND keeps what is there and writes after it. · WRITE começaria o arquivo vazio. APPEND mantém o que está lá e escreve após ele.
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.
Lendo cada linha
OPENFILE "data.txt" FOR READ
WHILE NOT EOF("data.txt") DO
READFILE "data.txt", LineString
OUTPUT LineString
ENDWHILE
CLOSEFILE "data.txt"
EOFtesta o fim de arquivo 文件结束. Teste antes de cada leitura; ler além do final é um erro.CLOSEFILEimporta: dados em buffer podem ser perdidos e outros programas bloqueados ao deixar um arquivo aberto.
Handling a file: open → use → close · Gerenciamento de arquivo: abrir → usar → fechar
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. · Passe pelo ciclo de vida que todo arquivo segue. As duas partes fáceis de esquecer são testar EOF ao ler em um laço e sempre fechar no final.
What does EOF test for? · O que EOF testa?
EOF (end of file) is checked before each read so the loop stops when there is no more data. · EOF (fim de arquivo) é verificado antes de cada leitura para que o laço pare quando não houver mais dados.
Why must you always close a file after using it? · Por que você deve sempre fechar um arquivo após usá-lo?
Closing flushes buffered writes to disk and releases the lock so other programs can use the file. · Fechar grava writes bufferadas em disco e libera o bloqueio para que outros programas possam usar o arquivo.
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.
Escrevendo linhas
OPENFILE "log.txt" FOR WRITE
FOR i ← 1 TO 100
WRITEFILE "log.txt", "Event " & NUM_TO_STR(i)
NEXT i
CLOSEFILE "log.txt"
WRITEinicia o arquivo vazio. Para adicionar a um registro que deve manter seu histórico, abra-oFOR APPENDem vez disso.- Um arquivo de texto contém strings: um número é convertido com
NUM_TO_STRna saída.
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.
Exemplo resolvido: as últimas três linhas de um arquivo
- Escreva um procedimento
LastLines(FileName)que exiba as últimas três linhas de um arquivo de texto, na ordem.
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 nova linha empurra as anteriores, então em
EOFas três variáveis contêm as últimas três linhas; um arquivo mais curto exibe strings vazias. Para as cinco primeiras linhas, conte as leituras e pare em cinco ou emEOF, o que ocorrer primeiro. Um arquivo vazio tornaEOFverdadeiro imediatamente após abrir.
Put the steps of the LastLines procedure in order. · Coloque as etapas do procedimento LastLines em ordem.
Initialise, open, loop with the shift before the read, close, output. Shifting after the read would lose the newest line. · Inicialize, abra, faça o laço com o deslocamento antes da leitura,file, exiba. Deslocar após a leitura perderia a nova linha.
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 em uma linha
- Um registro é escrito como uma linha, seus campos unidos por um caractere separador 分隔符, e cada número ou Boolean convertido com
NUM_TO_STR(e lido novamente comSTR_TO_NUM, ou comparando com"TRUE"). - Escolha um separador que possa nunca aparecer nos dados: uma vírgula ou
|para nomes e números; nunca um espaço quando um nome pode conter um. - Ler novamente: leia a linha, divida-a no separador, converta cada campo para seu tipo, armazene-o no registro.

Junte com um separador para escrever; divida e converta para ler
A line stores a player's full name and score. Which separator is the safest choice? · Uma linha armazena o nome completo e a pontuação de um jogador. Qual separador é a escolha mais segura?
The separator must never occur inside a field. A full name contains a space, and a score contains digits. · O separador nunca deve ocorrer dentro de um campo. Um nome completo contém um espaço, e uma pontuação contém dígitos.
An INTEGER can be written to a text file directly, without converting it to a string first. · Um INTEGER pode ser escrito diretamente em um arquivo de texto, sem convertê-lo para string primeiro.
A text file holds lines of characters. Convert with NUM_TO_STR to write and STR_TO_NUM to read back. · Um arquivo de texto segura linhas de caracteres. Converta com NUM_TO_STR para escrever e STR_TO_NUM para ler de volta.
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.
Exemplo resolvido: salvar um registro, carregá-lo de volta
- Um registro
Playertem camposName : STRINGeScore : INTEGER. Escreva pseudocódigo para anexá-lo ascores.txtcomo uma linha, e para ler uma linha de volta para o 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"
- As notas: o modo correto, a conversão do número em ambas as direções, um separador que não pode ocorrer em um nome, e ambos os arquivos fechados.
To store a record as one line of a text file, a program must: select all · todos that apply. · Para armazenar um registro como uma linha de um arquivo de texto, um programa deve: selecione todos que se aplicam.
Convert, join, write, close. A text file has no binary layout; that is what a binary file would do. · Converter, juntar, escrever, file. Um arquivo de texto não tem layout binário; isso é o que um arquivo binário faria.
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.
Acesso serial e direto
- Um arquivo de texto é serial 顺序 (sequencial): ele é lido na ordem do início, então encontrar uma linha significa ler todas as linhas anteriores.
- O acesso direto (aleatório) salta diretamente para um registro em uma posição calculada sem ler os outros; precisa de registros de comprimento fixo, que arquivos de texto não têm.
- Para o currículo, o loop de arquivo de texto acima é o modelo: abra, teste
EOF, leia, feche.
Direct (random) access lets a program jump straight to a record without reading the others first. · Acesso direto (aleatório) permite que um programa pule diretamente para um registro sem ler os outros primeiro.
Serial access must read from the start. · Acesso serial deve ler do início.
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.
Marcas que escapam
- Ler além do final. Teste
EOFantes de cadaREADFILE. - Abrir
FOR WRITEquando o arquivo deve manter seu conteúdo. Isso éAPPEND. - Escrever um número sem
NUM_TO_STR, ou lê-lo de volta semSTR_TO_NUM. Um arquivo de texto contém strings. - Esquecer
CLOSEFILE, ou usar um arquivo antes deOPENFILE. Ambos perdem a nota pelo manuseio de arquivos.
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
Entendeu?
- arquivos dão persistência: dados sobrevivem ao fim do programa, podem ser compartilhados e podem exceder a memória
OPENFILE … FOR READ | WRITE | APPEND→READFILE/WRITEFILE→CLOSEFILE;WRITEsobrescreve,APPENDadiciona no final- teste
EOFantes de cada leitura; converta números comNUM_TO_STRpara fora eSTR_TO_NUMde volta - um registro = uma linha, campos unidos por um separador que nunca aparece nos dados