파일(File)
도입됨
17:29
데이터 타입 및 구조
프로그램이 저장하는 모든 값에는 데이터 타입이 필요합니다. 올바른 타입을 선택하는 것은 중요합니다. 예를 들어, 품목의 재고 여부를 저장한다고 해 봅시다. 'yes'라는 단어를 입력할 수도 있습니다…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| games console | A device that runs video games and connects to a screen. |
| cartridge | A removable device that stores a game for a games console. |
| bytes | Units of eight bits used to store data in a computer. |
| save/seɪv/ | To store data so that it can be used later. |
| document/ˈdɒkjuːmənt/ | A file containing information created or edited by a user. |
| RAM/ræm/ | Random-access memory used for working data and instructions, usually losing its contents when power is removed. |
| file/faɪl/ | 파일 |
| pseudocode/ˈsuːdəʊkəʊd/ | A language-independent description of an algorithm using structured, programming-like statements. |
| text file/tekst faɪl/ | 텍스트 파일 |
| Variables/ˈveərɪəblz/ | A quantity or named value that can change or take different values. |
| secondary storage/ˈsekəndəri ˈstɔːrɪdʒ/ | 보조 저장장치 |
| persistence/pəˈsɪstəns/ | 지속성 |
| memory/ˈmeməri/ | The part of a computer that holds data and programs currently in use. |
| mode/məʊd/ | A setting that determines how a file is opened or used, such as reading, writing or appending. |
| characters/ˈkærɪktəz/ | A text unit such as a letter, digit, punctuation mark or other symbol. |
| loop/luːp/ | A structure that repeats a sequence of instructions. |
| overwrites | Replaces the existing contents of a file with new data. |
| end of file/end ɒv faɪl/ | 파일 끝 |
| buffered data | Data held temporarily in memory before it is written to a file. |
| strings/strɪŋz/ | Sequences of characters used as text in a program. |
| procedure/prəˈsiːdʒə/ | A named sequence of instructions that performs a task when called. |
| empty strings | Text values that contain no characters at all. |
| fields/fiːldz/ | Parts of a database record that each hold one item of data. |
| record/ˈrekɔːd/ | A stored collection of information about an item, person or event. |
| separator/ˈsepəreɪtə/ | 구분자 |
| Boolean/ˈbuːlɪən/ | A logical value that is either true or false. |
| escaping scheme | A set of rules for writing special characters so they are read correctly. |
| type/taɪp/ | A category of data that determines what values it can hold. |
| serial/ˈsɪərɪəl/ | Describes access to data in order, starting at the beginning of a file. |
| sequential/siːˈkwenʃl/ | 순차적 |
| Direct (random) access | A way to reach a record at a calculated position without reading earlier records. |
| fixed-length records | Records that all take up the same amount of storage space. |
기억력 게임
- 1987년까지 게임 콘솔을 끄면 모든 데이터가 지워졌습니다. 모든 세션이 첫 화면에서 시작했으므로, 긴 게임은 긴 오후나 아예 없었습니다.
- 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.
- 모든 고점 기록, 모든 문서, 모든 설정이 존재하는 이유는 동일함: RAM은 전원 차단 시 기억을 잃지만, 파일은 그렇지 않음.
- 이 수업이 파일이 존재하는 이유와 pseudocode가 텍스트 파일을 줄 단위로 읽고 쓰는 방법을 설명합니다.
파일이 필요한 이유
- 변수는 RAM에 존재하며 프로그램 종료 시 사라짐. 이중 저장장치 위의 파일은 프로그램 실행 간 데이터 유지: 영속성.
- 파일은 한 프로그램의 출력을 다른 프로그램의 입력으로 만들어, 데이터를 **공유(shared)**할 수 있게 합니다.
- 파일은 메모리보다 더 많은 용량을 가질 수 있으며, 프로그램은 저장된 상태로부터 **재시작(restart)**할 수 있습니다.

변수는 실행 종료 시 사라지며, 파일은 내일도 그대로 존재함

Why does a program write data to a file rather than keeping it in a variable?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
RAM is volatile, so data is lost on exit. A file on secondary storage persists between runs.
텍스트 파일과 세 가지 모드
- **텍스트 파일(text file)**은 문자들의 줄로 데이터를 저장하며, 프로그램은 시작부터 줄 단위로 읽고 씁니다. 이 줄의 서열이 루프를 통해 처리하게 합니다.
OPENFILE … FOR READ은 첫 번째 줄을 읽습니다.FOR WRITE은 새 파일을 생성하거나 기존 파일을 위저라이트합니다.FOR APPEND은 기존 내용을 유지한 채 끝에 새로운 줄을 추가합니다.- Open before use, close after. A file has one mode at a time.

Match each file-open mode to what it does.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
READ reads; WRITE replaces from scratch; APPEND adds to the end without losing what is there.
To add lines to the end of an existing file without losing its contents, open it FOR ____.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
WRITE would start the file empty. APPEND keeps what is there and writes after it.
모든 줄 읽기
OPENFILE "data.txt" FOR READ
WHILE NOT EOF("data.txt") DO
READFILE "data.txt", LineString
OUTPUT LineString
ENDWHILE
CLOSEFILE "data.txt"
EOF는 **파일 끝(end of file)**을 테스트합니다. 각 읽기 전에 테스트하십시오: 끝을 넘어 읽기는 오류입니다.CLOSEFILE가 중요합니다: 버퍼링된 데이터가 손실되거나 다른 프로그램이 열린 파일을 접근할 수 없게 됩니다.
Handling a file: open → use → close
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.
What does EOF test for?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
EOF (end of file) is checked before each read so the loop stops when there is no more data.
Why must you always close a file after using it?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Closing flushes buffered writes to disk and releases the lock so other programs can use the file.
줄 쓰기
OPENFILE "log.txt" FOR WRITE
FOR i ← 1 TO 100
WRITEFILE "log.txt", "Event " & NUM_TO_STR(i)
NEXT i
CLOSEFILE "log.txt"
WRITE으로 파일을 비우기 시작함. 이력을 유지해야 하는 로그에 추가하려면FOR APPEND으로 여는 것이 좋음.- 텍스트 파일은 문자열을 보관함: 숫자는 출력 시
NUM_TO_STR으로 변환됨.
worked example: 파일의 마지막 세 줄
- 텍스트 파일의 마지막 세 줄을 순서대로 출력하는 procedures
LastLines(FileName)를 작성하십시오.
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
- 새 줄이 추가될 때마다 이전 줄들이 밀려나므로,
EOF지점에서 세 변수는 마지막 세 줄을 보유함; 짧은 파일은 빈 문자열을 출력함. 첫 다섯 줄에 대해서는 읽기 횟수를 세어 5번이나EOF중 먼저 오는 지점에서 멈춤. 빈 파일은 열기 직후EOF을 참으로 만듦.

Put the steps of the LastLines procedure in order.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Initialise, open, loop with the shift before the read, close, output. Shifting after the read would lose the newest line.
줄의 필드(fields)
- 레코드는 한 줄로 기록되며, 필드는 구분자 문자로 연결되고, 각 숫자 및 부울린은
NUM_TO_STR(또는"TRUE"과 비교하여)으로 변환되어 (STR_TO_NUM로 다시 읽힘). - 데이터에 절대 나타날 수 없는 구분자를 선택합니다: 이름과 숫자에는 쉼표나
|을 사용하되, 이름에 공백이 포함될 수 있다면 공백은 절대 사용하지 않습니다. - 다시 읽기: 줄을 읽고 구분자에서 분리하며, 각 필드의 유형으로 변환하여 레코드에 저장합니다.

쓰기는 구분자로 연결하고, 읽기는 분리하여 유형으로 변환합니다

A line stores a player's full name and score. Which separator is the safest choice?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
The separator must never occur inside a field. A full name contains a space, and a score contains digits.
An INTEGER can be written to a text file directly, without converting it to a string first.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
A text file holds lines of characters. Convert with NUM_TO_STR to write and STR_TO_NUM to read back.
worked example: 레코드 저장 및 다시 불러오기
- 레코드
Player에는 필드Name : STRING과Score : INTEGER이 있습니다. 이를scores.txt에 한 줄로 추가하는 가상 코드(pseudocode)를 작성하고, 한 줄을 다시 레코드에 읽어들이는 가상 코드를 작성하십시오.
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"
- 점수 기준: 올바른 모드, 양방향 숫자 변환, 이름에 포함될 수 없는 구분자, 그리고 두 파일이 모두 닫혀 있음.

To store a record as one line of a text file, a program must: select 모든 that apply.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
Convert, join, write, close. A text file has no binary layout; that is what a binary file would do.
직렬 및 직접 접근
- 텍스트 파일은 직렬(순차)입니다: 시작점에서 순서대로 읽으므로 특정 줄을 찾으려면 그 이전의 모든 줄을 읽어야 합니다.
- 직접(무작위) 접근은 다른 줄을 읽지 않고 계산된 위치로 바로 레코드에 도달할 수 있습니다. 이는 고정 길이 레코드가 필요하므로 텍스트 파일에는 적용되지 않습니다.
- 교육 과정에서는 위의 텍스트 파일 루프가 표준 모델입니다: 열고,
EOF를 테스트하고, 읽고, 닫습니다.

Direct (random) access lets a program jump straight to a record without reading the others first.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Serial access must read from the start.
놓칠 수 있는 점
- 끝을 넘어 읽기.
READFILE를 수행하기 전에 반드시EOF를 테스트하십시오. - 파일의 내용을 유지해야 할 때
FOR WRITE를 엽니다. 이것이APPEND입니다. NUM_TO_STR없이 숫자를 쓰거나,STR_TO_NUM없이 다시 읽기. 텍스트 파일은 문자열만 저장합니다.CLOSEFILE를 잊거나,OPENFILE전에 파일을 사용합니다. 둘 다 파일 처리 점수를 잃게 됩니다.
이해했습니다
- 파일은 지속성(persistence) 을 제공합니다: 프로그램 종료 후에도 데이터가 보존되며, 공유 가능하며, 메모리 용량을 초과할 수 있습니다.
OPENFILE … FOR READ | WRITE | APPEND→READFILE/WRITEFILE→CLOSEFILE;WRITEoverwrites,APPENDadds at the end- 각 읽기 전에
EOF을 테스트; 숫자는 출력 시NUM_TO_STR, 반환 시STR_TO_NUM으로 변환 - 한 레코드 = 한 줄, 데이터에 절대 등장하지 않는 구분자로 필드 연결
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.