fputs()
fputs() はストリームに文字列を書き込む。
int fputs(char *文字列, FILE *ストリーム);
fputs() は書き込みが成功すると負でない値を返し、エラーが発生すると EOF を返す。文字列の終端にあるヌル文字は書き込まれず、改行文字が追加されることもない。
fgets()
char *fgets(char *文字列, int 数値, FILE *ストリーム);
fgets() はストリームから文字を読み込み、文字列に書き込んでいく。この動作は、
- 数値 – 1 個分の文字を読む
- 改行文字に出会う
- ファイルの終わりに達する
まで続けられる。どの場合にも、文字列の終端にはヌル文字が付け加えられる。
fgets() は成功すると文字列へのポインタを返し、エラーが発生するとヌルポインタを返す。
例1
次のプログラムは、キーボードから入力された文字列を読み込み、ファイルへ保存する。そしてファイルを開きなおして、内容を表示する。
#include
#include
#include
int main(int argc, char *argv[])
{
FILE *fp;
char str[80];
/* check parameters */
if (argc != 2) {
printf("Specify file name\n");
exit(1);
}
/* open file to write */
if ((fp = fopen(argv[1], "w")) == NULL) {
printf("Cannot open file: %s\n", argv[1]);
exit(1);
}
printf("Input string. Empty to quit.\n");
do {
printf(": ");
gets(str);
strcat(str, "\n");
if (*str != '\n') {
fputs(str, fp);
}
} while (*str != '\n');
fclose(fp);
/* open file to read */
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("Cannot open file %s\n", argv[1]);
exit(1);
}
/* read from file */
do {
fgets(str, 80, fp);
if (!feof(fp)) {
printf("%s", str);
}
} while (!feof(fp));
fclose(fp);
return 0;
}
takatoh@nightschool $ ./sample_9_4a sample_9_4a.txt Input string. Empty to quit. : Hello : I'm takatoh : How are you? : Hello I'm takatoh How are you? takatoh@nightschool $ cat sample_9_4a.txt Hello I'm takatoh How are you?
fprintf()とfscanf()
これらは printf() と scnf() のストリーム版だ。コンソールから入出力する代わりに、ストリームから入出力する。
int fprintf(FILE *ストリーム, char *制御文字列, ...); int fscanf(FILE *ストリーム, char *制御文字列, ...);
例2
次のプログラムは、double 値と int 値と文字列をコマンドラインで指定されたファイルに書き込み、それから、ファイルから読み込みなおして表示する。
#include
#include
#include
int main(int argc, char *argv[])
{
FILE *fp;
double ld;
int d;
char str[80];
/* chech parameters */
if (argc != 2) {
printf("Specify file name\n");
exit(1);
}
/* open file to write */
if ((fp = fopen(argv[1], "w")) == NULL) {
printf("Cannot open file: %s\n", argv[1]);
exit(1);
}
fprintf(fp, "%f %d %s", 12345.342, 1908, "hello");
fclose(fp);
/* open file to read */
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("Cannot open file: %s\n", argv[1]);
exit(1);
}
fscanf(fp, "%lf%d%s", &ld, &d, str);
printf("%f %d %s\n", ld, d, str);
fclose(fp);
return 0;
}
takatoh@nightschool $ ./sample_9_4b Specify file name takatoh@nightschool $ ./sample_9_4b sample_9_4b.txt 12345.342000 1908 hello takatoh@nightschool $ cat sample_9_4b.txt 12345.342000 1908 hellotakatoh@nightschool $
書き込んだファイルの最後に改行文字がついてないせいで次のプロンプトが表示されちゃてるけど、画面に表示されるのと同じように、ファイルにも書き込まれているのがわかる。