このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
ファイルはプログラム終了後もデータを保持する
- ファイルはディスク上にデータを保存するため、プログラムが停止してもデータが残ります。
- ファイルは
FILE *を通じて操作します。これはfopenから得られるポインタです。 - これらのタスクでは、ファイルに書き込み、同じプログラム内で読み戻すため、すべてを自身で完結させます。
探索
Writing then reading a file
A file is used in three steps: 開く it with fopen, read or write, then 閉じる it with fclose.
開閉処理
fopen("data.txt", "w")はファイルを開いて書き込みモードにします(既存のファイルは作成または空にします)。fopen("data.txt", "r")はファイルを開いて読み込みモードにします。- 作業が終わったら必ず
fclose(f)を呼び出してデータを保存し、ファイルを解放してください。
fprintf による書き込み
fprintfはprintfと同様の働きをしますが、最初の引数はFILE *です。fprintf(f, "%d\n", x);は数値xと改行をファイルfに書き込みます。- 各値を別々の行に書き込むと、後から読み戻しやすいです。
fscanf と fgets による読み込み
fscanf(f, "%d", &x)は1つの数値を読み込み、成功すると1を返します。fgets(buf, size, f)はテキストの1行をbufに読み込み、末尾でNULLを返します。- 読み込みが失敗するまでループして、ファイル全体を処理します。
English
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
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;
}
よくあるミス
- 読み込みや書き込みの前に、
fopenがNULLを返していないか確認してください。 - 作業が終わったら必ず
fcloseを呼び出してファイルを閉じてください。
あなたも試してみよう
- これらのタスクは完全なプログラムです:
mainの内部に記述し、回答を確認で出力をテストします。 - まずファイルを書き込み、
fcloseで閉じ、その後読み込みモードで再度開いて、読み込みが失敗するまでループします。
難易度 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).
実行ボタンをクリックして出力を確認してください。