File processing
도입됨
13:52
프로그래밍 패러다임
여기에 한 가지 과제가 있습니다: A 등급을 받은 모든 학생을 나열하십시오. 한 프로그래머는 루프를 작성합니다 — 첫 번째 레코드에서 시작하여, 등급을 확인하고, 이름을 목록에 추가하고, 이동…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| text file/tekst faɪl/ | A file that stores data as a sequence of encoded characters. |
| stream of characters | A sequence of characters stored one after another in a file. |
| byte/baɪt/ | A group of eight bits, commonly used as a unit of data storage. |
| file operations | Actions a program performs on files, such as reading and writing. |
| APPEND/əˈpend/ | 추가 |
| file layout | The way data and records are organised within a file. |
| access method/ˈækses ˈmeθəd/ | A way of reaching and reading records stored in a file. |
| sequential access/siːˈkwenʃl ˈækses/ | Reading records in order from the start until the wanted record is reached. |
| text records | Units of information stored as text, often one per line in a file. |
| flag/flæɡ/ | A stored indicator of a condition or state, often represented by a Boolean value or a single bit. |
| loop/luːp/ | A structure that repeats a sequence of instructions. |
| temporary file/ˈtemprəri faɪl/ | 임시 파일 |
| sequential update | Changing records by reading them in order and writing the updated results. |
| record/ˈrekɔːd/ | A stored collection of information about an item, person or event. |
| delete/dɪˈliːt/ | To remove a record from a table. |
| insert/ˈɪnsɜːt/ | To add a new item to a data structure, file or table. |
| Hard-coded paths | Put the filename in a constant so it appears once and the program can be moved. |
| filename | The name used to identify a file when accessing it. |
| constant/ˈkɒnstənt/ | A named or literal value that does not change during the relevant part of a program. |
| mode/məʊd/ | A setting that determines how a file is opened or used, such as reading, writing or appending. |
| log/lɒɡ/ | A record of events and actions on a computer system. |
| overwrite/ˌəʊvəˈraɪt/ | 덮어쓰기 |
| configuration file | A file that stores settings a program uses when it runs. |
텍스트 파일의 한 줄을 변경할 수 없음
- 프로그램은 고객 파일 중간에 오타를 수정해야 합니다. 명백해 보입니다: 라인을 찾고, 수정하고, 저장하세요.
- 거의 모든 언어는 이를 허용하지 않습니다. 텍스트 파일은 문자의 스트림이며, 수정된 이름은 이전 이름과 길이가 다르므로 이후의 모든 바이트를 이동시켜야 합니다.
- 따라서 표준 답안은 편집하지 않는 것입니다: 전체 파일을 복사하여 passes할 때 해당 줄 하나만 변경하고, 복사를 원본 위에 배치합니다.
- 이 수업은 파일 조작, 업데이트를 위한 copy-through 패턴, 그리고 실제 버그를 유발하는 함정들입니다.

조작 방법
OPENFILE name FOR READ | WRITE | APPEND이 파일을 엽니다. READ는 시작점에서 기존 파일을 열고, WRITE는 파일을 생성하거나 기존 파일을 위변조하며, APPEND는 파일을 열고 끝에 추가합니다.READFILE name, variable이 다음 줄을 읽습니다.WRITEFILE name, value이 한 줄을 씁니다.CLOSEFILE name이 닫습니다.EOF(name)은 끝이 도달되었을 때 TRUE입니다.- 먼저 파일 레이아웃과 접근 방식을 선택하십시오: 직렬, 순차 및 무작위 파일은 서로 다른 작업에 사용됩니다. 여기의 복사-통과(copy-through) 예제는 텍스트 레코드에 대해 순차적 접근을 사용합니다.
- 전체 파일을 읽는 패턴은 항상 동일합니다:
OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt") DO
READFILE "names.txt", thisName
OUTPUT thisName
ENDWHILE
CLOSEFILE "names.txt"

매번 열기, 사용, 닫기


File access route
Follow a file from storage to program and back safely.
What does opening a file FOR WRITE do to existing contents?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
WRITE creates or overwrites the file. To keep existing contents and add more, use APPEND.
Match each file operation to what it does.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
WRITE overwrites, APPEND adds; EOF marks the end; the search loop stops early once the value is found.
파일 검색
- 검색하려면 줄 단위로 읽고 목표가 발견되면 멈춥니다. 두 가지 조건이 필요합니다:
WHILE NOT EOF(…) AND NOT found. 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:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Stopping when found avoids reading the rest of the file unnecessarily.
Why does a file search loop use WHILE NOT EOF AND NOT found? Select 모든 that apply.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Every file must still be closed. The two conditions handle early exit and the end of the file respectively.
업데이트: 임시 파일 패턴
- 텍스트 파일은 인플레이스(in-place)로 편집할 수 없으므로, 업데이트에는 임시 파일을 사용합니다.
- 원본 파일을 FOR READ로 열고, 임시 파일을 FOR WRITE로 엽니다. 각 줄을 순서대로 읽어, 변경된 경우나 변경되지 않은 경우를 가리지 않고 임시 파일에 씁니다.
- 두 파일을 모두 닫은 후, 원본 파일을 임시 파일로 교체합니다.
- 동일한 패턴으로 모든 작업을 수행할 수 있습니다: 기록을 삭제하려면 해당 줄을 쓰기하지 않고 건너뛰고, 삽입하려면 복사하는 과정에서 올바른 지점에 새로운 줄을 씁니다.

To update a text file when in-place editing is not possible, you:
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Copy each line (changed or not) to a temp file, then swap it in for the original.
Put the steps of deleting one record from a text file in order.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
The last step is the one candidates leave out, and without it nothing has changed. The same pattern inserts or edits a record.
worked example: 기록 삭제
- 프로그램이 텍스트 파일에서 한 개의 기록을 삭제하는 방법을 설명하십시오. [4]
- 원본 파일을 읽기 모드로 열고, 임시 파일을 쓰기 모드로 엽니다.
- 각 줄을 순서대로 읽습니다. 그 줄이 삭제해야 할 줄이 아니라면临时 파일에 쓰고, 만약 삭제해야 할 줄이라면 쓰지 않습니다.
- 원본 파일의 끝(EOF)에 도달하면 두 파일을 모두 닫습니다.
- 원본 파일을 임시 파일로 교체합니다. 네 단계 모두 점수를 받으며, 마지막 단계는 응시자가 자주 잊어버리는 부분입니다.

A program writes 500 records then ends without closing the file, and the last few are missing. Why?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Writes are buffered for speed. Closing the file flushes the buffer, and it may also release a lock other programs are waiting on.
주의사항
- 파일을 닫지 않는 것: 버퍼링된 데이터가 Writers되지 않아 마지막 기록들이 사라지고, 다른 프로그램으로부터 파일 잠금 상태가 유지될 수 있습니다.
- APPEND를 의도했을 때 FOR WRITE로 열기: 파일이 열리자마자 모든 기존 내용이 파괴되며, 단 하나의 줄도 쓰기 전에 이미 사라짐.
- EOF를 넘어서 읽기: 읽기 전에
EOF를 테스트하고, 읽기 후에 테스트하지 마십시오. - 하드코딩된 경로: 파일 이름을 상수에 배치하여 한 번만 표시되도록 하고, 프로그램을 이동할 수 있게 하십시오.
Forgetting to close a file can lose buffered writes and lock other programs out — so you should always close a file when finished.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Closing flushes buffered data to disk and releases the lock — a FINALLY block is a good place to guarantee it.
To add today's entries to a log that must keep its history, open the file FOR ____.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
WRITE would destroy every previous entry the instant the file was opened, before a single line was written.
worked example: 어떤 모드인가
- 오늘의 거래 내역을 역사 기록을 유지해야 하는 로깅 파일에 추가하는 프로그램 APPEND: WRITE를 사용하면 이전 기록이 모두 파괴됩니다.
- 매일 밤 새로운 리포트를 생성하여 어제의 것을 교체하는 프로그램 WRITE: 파일을 생성하거나 덮어쓰기는 정확히 원하는 작업입니다.
- 프로그램은 시작 시 설정 파일을 읽습니다. READ.
- 모드는 기존 내용에 대해 어떻게 처리해야 하는지에 따라 선택됩니다: 보존하고 추가하거나, 삭제하거나, 그대로 두거나.
놓칠 수 있는 점
- 업데이트 패턴은 임시 파일로 원본을 교체하는 것으로 끝납니다. 마지막 단계를 거치지 않고 복사만 하면 변경 사항이 없습니다.
- 검색 루프에는 두 가지 조건
NOT EOF과NOT found이 모두 필요하며, 이후에 테스트할 요소가 있어야 합니다. - WRITE는 덮어쓰기; APPEND는 추가합니다. 잘못 선택하면 열 때 파일을 파괴하게 됩니다.
- 항상
CLOSEFILE입니다. 그 이유를 말하세요: 그렇지 않으면 버퍼링된 데이터가 손실될 수 있습니다.
이해했습니다
OPENFILE … FOR READ | WRITE | APPEND, 그 다음READFILE또는WRITEFILE, 그 다음CLOSEFILE;EOF은 각 읽기 전에 테스트됩니다- WRITE는 생성하거나 덮어쓰고, APPEND는 내용을 유지하고 끝에 추가하며, READ는 시작 지점에서 읽습니다
WHILE NOT EOF AND NOT found와 함께 검색하여 루프가 조기에 종료되고 "발견되지 않음"을 보고할 수 있습니다- 임시 파일을 통해 복사하여 업데이트하며, 변경되거나 변하지 않은 줄을 각각 쓰고, 삭제할 줄은 건너뛰고 삽입할 줄은 추가한 뒤, 원본을 교체합니다
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.