fputc関数 - ファイルストリームに1文字書き込む
fputc関数を使うと、ファイルストリームに1文字書き込むことができます。
#include <stdio.h> int fputc(int c, FILE *fp);
第一引数は、書き込みたい文字です。第二引数は、ファイルストリームです。
ファイルを1文字づつ書き込むサンプル
fputc関数を使って、ファイルを1文字づつ書き込むサンプルです。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
// ファイルを読み込みモードで開く
const char* in_file = "input.txt";
FILE* in_fp = fopen(in_file, "r");
if (in_fp == NULL) {
fprintf(stderr, "Can't open file %s\n", in_file);
exit(1);
}
// ファイルを書き込みモードで開く
const char* out_file = "output.txt";
FILE* out_fp = fopen(out_file, "w");
if (out_fp == NULL) {
fprintf(stderr, "Can't open file %s\n", out_file);
exit(1);
}
// 読み込んで、ファイルにに出力
int32_t ch;
while(ch = fgetc(in_fp)) {
// EOFが返ってきた場合
if (ch == EOF) {
// ファイルの末尾かチェックする
if (feof(in_fp)) {
break;
}
}
fputc(ch, out_fp);
}
// fclose関数でファイルを閉じる
fclose(in_fp);
fclose(out_fp);
}
C言語ゼミ


