이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
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.

탐색하기
Writing then reading a file
A file is used in three steps: 열기(open) it with fopen, read or write, then 닫기(close) it with fclose.
English
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.
English
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.
English
Reading with fscanf and fgets
fscanf(f, "%d", &x)reads one number; it returns1when it succeeds.fgets(buf, size, f)reads up tosize - 1characters intobuf, stopping after a newline if one is encountered; it returnsNULLat end of file or on a read error.- Loop until the read fails to process the whole file.
English
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
if (f == NULL) {
printf("cannot open nums.txt for writing\n");
return 1;
}
fprintf(f, "3\n4\n");
fclose(f);
f = fopen("nums.txt", "r");
if (f == NULL) { // the file could not be opened
printf("cannot open nums.txt\n");
return 1;
}
int x, total = 0;
while (fscanf(f, "%d", &x) == 1) {
total += x;
}
fclose(f);
printf("%d\n", total); // 7
return 0;
}
English
Common mistakes
- Check that
fopendid not returnNULLbefore reading or writing. - Always
fclosethe file when you are done.
English
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.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
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).
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
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).
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
Mode "w" wipes a file; mode "a" appends to the end. The starter writes 10 및 20. Reopen scores.txt with "a", add the line 30, close it, then read every number back and print the total (60).
출력을 보려면 '실행'을 클릭하세요.