まぬねこの足跡。。。

備忘録+たのしさ+ひっそりと

C言語 ファイル操作

ファイル open close

FILE型のポインタ変数:ファイルポインタ

open

ファイルポインタ = fopen(ファイル名, モード);

FILE *file;
file = fopen("test.txt", "w");

close

fclose(ファイルポインタ);

FILE *file;
  :
fclose(file);

モード

モード(バイナリ) ファイルの扱い その他
rb 読込み ファイルがない時はNG。
wb 書込み 新規ファイル作成
ab 追記。 ファイルがない時は新規ファイル作成。
rb+ 読書き。 ファイルがない時はNG。
wb+ 読書き。 新規ファイル作成
ab+ 読込み+追記。 ファイルがない時は新規ファイル作成。

ファイルへの書き込み 書込み、追記モード時

テキストファイル

fprintf(ファイルポインタ, 変換識別子[, 格納する変数1…]);

int buf= 99;
FILE *file;
file = fopen("sample.txt", "w");
fprintf(file, "%d", buf);
fprintf(file, "Hello,world");
fclose(file);

sample.txt 表示イメージ

99Hello,world

バイナリーファイル

fwrite(書込む変数アドレス, 書込む変数のサイズ, 書込む項目数, ファイルポインタ);

int buf = 99;
FILE *file;
file = fopen("sample.txt", "wb");
fwrite(&buf, sizeof(buf), 1, file);
fclose(file);

sample.txt 表示イメージ

63 00 00 00 ←16進数 2桁区切り 表示

配列を1度で書き込む

int buf[] = {11, 22, 33, 44};
FILE *file;
file = fopen("sample.txt", "wb");
fwrite(&buf, sizeof(buf), 1, file);
fclose(file);

sample.txt 表示イメージ

63 00 00 00 16 00 00 00 21 00 00 00 2C 00 00 00 ←16進数 2桁区切り 表示

ファイルからの読込み 読込みモード時

fscanf(ファイルポインタ, 変換識別子[, 格納する変数1…]);

int buf;
FILE *file;
file = fopen("sample.txt", "r");
fscanf(file, "%d", &buf); ←%d:数値以外は無視する
fclose(file);
printf("%d\n", buf);

sample.txt 表示イメージ

999

表示イメージ

999

CSVファイル

int bufA, bufB;
FILE *file;
file = fopen("sample.txt", "r");
fscanf(file, "%d,%d", &bufA, &bufB); ←%d:数値以外は無視する
fclose(file);
printf("%d %d\n", bufA, bufB);

sample.txt 表示イメージ

999,888

表示イメージ

999 888

バイナリーファイル

fread(読込む変数のポインタ,読込む変数のサイズ, 読込む項目数, ファイルポインタ);

int buf;
FILE *file;
file = fopen("sample.txt", "rb");
fread(&buf, sizeof(buf), 1, file);
fclose(file);
printf("%d\n", buf);

sample.txt 表示イメージ

63 00 00 00

表示イメージ

11