Text files: write then read · 텍스트 파일: 쓰기 이후 읽기
Files keep data after the program ends
- A file stores data on disk, so it is still there after your program stops.
- You work with a file through a
FILE *— a pointer you get fromfopen. - In these tasks you write a file, then read it back in the same program, so everything is self-contained.
파일은 프로그램 종료 후에도 데이터를 유지합니다
- 파일(file) 은 디스크에 데이터를 저장하므로, 프로그램이 멈춘 후에도 여전히 존재합니다.
- 파일은
FILE *를 통해 작업합니다 — 이는fopen으로부터 얻은 포인터입니다. - 이 작업에서는 파일을 쓰고, 같은 프로그램 내에서 다시 읽어 모든 것을 자체적으로完성합니다.
Writing then reading a file · 파일을 쓴 후 읽기
A file is used in three steps: open it with fopen, read or write, then close it with fclose. · 파일 사용은 세 단계로 이루어집니다: fopen으로 열기, 읽기 또는 쓰기, 그리고 fclose로 닫기입니다.
Opening and closing
fopen("data.txt", "w")opens a file for writing (it creates or empties the file).fopen("data.txt", "r")opens it for reading.- Always
fclose(f)when you are done, so the data is saved and the file is released.
열고 닫기
fopen("data.txt", "w")는 쓰기(write) 용으로 파일을 엽니다 (파일을 생성하거나 비웁니다).fopen("data.txt", "r")는 읽기(read) 용으로 파일을 엽니다.- 완료 시 항상
fclose(f)하여 데이터를 저장하고 파일을 해제합니다.
Writing with fprintf
fprintfworks likeprintf, but its first argument is theFILE *.fprintf(f, "%d\n", x);writes the numberxand a newline into the filef.- Write each value on its own line so it is easy to read back.
fprintf를 통한 쓰기
fprintf는printf과 유사하게 작동하지만, 첫 번째 인수는FILE *입니다.fprintf(f, "%d\n", x);은 숫자x와 줄바꿈을 파일f에 씁니다.- 각 값을 별도의 줄에 써서 읽기 쉽게 만듭니다.
Reading with fscanf and fgets
fscanf(f, "%d", &x)reads one number; it returns1when it succeeds.fgets(buf, size, f)reads one line of text intobuf; it returnsNULLat the end.- Loop until the read fails to process the whole file.
fscanf와 fgets를 통한 읽기
fscanf(f, "%d", &x)는 한 숫자를 읽습니다. 성공하면1을 반환합니다.fgets(buf, size, f)는 텍스트의 한 줄(line) 을buf에 읽습니다. 끝이 오면NULL을 반환합니다.- 읽기가 실패할 때까지 반복하여 전체 파일을 처리합니다.
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
fprintf(f, "3\n4\n");
fclose(f);
f = fopen("nums.txt", "r");
int x, total = 0;
while (fscanf(f, "%d", &x) == 1) {
total += x;
}
fclose(f);
printf("%d\n", total); // 7
return 0;
}
Common mistakes
- Check that
fopendid not returnNULLbefore reading or writing. - Always
fclosethe file when you are done.
흔한 실수
- 읽거나 쓰기 전에
fopen가NULL을 반환하지 않았는지 확인하십시오. - 완료 시 항상 파일을
fclose합니다.
Now you try
- These tasks are full programs: write inside
main, and Check answer tests the output. - Write the file first,
fcloseit, then open it again for reading and loop until the read fails.
이제 직접 해보기
- 이 작업들은 완전한 프로그램입니다:
main내부에 작성하고, Answer Check가 출력을 검증합니다. - 파일을 먼저 쓰고,
fclose로 닫은 뒤, 다시 읽기용으로 열어 읽기가 실패할 때까지 루프합니다.
In main: write the numbers 10, 20, 5, 7 (one per line) to a file, close it, then open it again and add them up with fscanf. Print the total (42). · main에서 숫자 10, 20, 5, 7(줄마다 하나씩)을 파일에 쓰고, 닫은 후 다시 열어 fscanf으로 합산하십시오. 총합(42)을 출력하십시오.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
In main: write three lines of text to a file, close it, then open it again and count the lines with fgets. Print the count (3). · main에서 텍스트 줄 세 개를 파일에 쓰고, 닫은 후 다시 열어 fgets으로 줄을 세십시오. 개수(3)를 출력하십시오.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.