#include <stdio.h> #include <stdlib.h> #include <string.h> #define f_name "sample.txt" /* 作成するファイルの名前 */ int main(void){ int i, len; char str[ ] = "abcdefgh", /* ファイルに書き込む文字列 */ ch; FILE *fp; /* ファイルポインタ */ /*** ファイルが存在するときは内容を表示して終了 ***/ fp = fopen(f_name, "r"); /* ファイルを読み込み用にオープン */ if (fp != NULL){ /* ファイルが存在する */ ch = fgetc(fp); printf("file exists!!\n"); while(ch != EOF){ putchar(ch); ch = fgetc(fp); } fclose(fp); exit(1); /* プログラムの終了 */ } /*** ファイルが存在しないときは書き込む ***/ len = strlen(str); /* 書き込む文字列の長さ計算 */ fp = fopen(f_name, "w"); for (i=0; i<= len; i++){ ch = str[i]; fputc(ch, fp); } fputc('\n', fp); fclose(fp); }
2003年5月3日 13:02 更新