C言語Ⅱ 演習(3-5) ~ファイル(5)~ 解答例 1
C
言語Ⅱ
演習
(3-5)
~ファイル
(5)
~
教科書
13章
*以下 プログラム例 あ ,全く同 あ 必要 あ ません.プログラム作成 参考 確認 ください.
問題 .
// 演習(3-5) ファイル 問題
#include<stdio.h>
#include<stdlib.h> //exit(1);用
int main(void){ FILE *fp; int data[5]; int i;
printf("test451.txtからデータ 読 込 。\n"); if( (fp=fopen("test451.txt","r")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
for(i=0;i<5;i++){
fscanf(fp,"%d", &data[i]); }
fclose(fp);
printf("test451.txtにデータ 書き込 。\n"); if( (fp=fopen("test451.txt","w")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
for(i=0;i<5;i++){
fprintf(fp," %2d", data[i]*2); }
fclose(fp);
return 0; }
問題 .
// 演習(3-5) ファイル 問題
#include<stdio.h>
#include<stdlib.h> //exit(1);用
int main(void){ FILE *fp; double data[5];
double sum=0.0, ave; int i;
printf("test452a.txtからデータ 読 込 。\n");
if( (fp=fopen("test452a.txt","r")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
for(i=0;i<5;i++){
fscanf(fp,"%lf", &data[i]);
}
fclose(fp);
printf("test452b.txtにデータ 書き込 。\n"); if( (fp=fopen("test452b.txt","w")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
for(i=0;i<5;i++){ sum=sum+data[i]; }
ave=sum/5;
fprintf(fp,"平均値:%f", ave); fclose(fp);
return 0; }
問題 .
// 演習(3-5) ファイル 問題
#include<stdio.h>
#include<stdlib.h> //exit(1);用
int main(void){ FILE *fp;
char filename[256]; char ch;
printf("ファイル名 入力し く さい。\n"); scanf("%s", filename);
printf("%sファイル 開き 。\n", filename); printf("---\n");
if( (fp=fopen(filename,"r")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
for(;;){ //①
if( (fscanf(fp,"%c", &ch))==EOF ) break; //①
printf("%c", ch); //①
} //①
fclose(fp);
printf("\n"); //工夫点:最後に改行 入
return 0; }
別解 ※上記① 部分 次 い か 解答例に置き換え も良い。
C言語Ⅱ 演習(3-5) ~ファイル(5)~ 解答例 2
[解答例 ]:無限ループ(while)+終了条件 脱出
while(1) {
if( fscanf(fp,"%c",&ch)==EOF ) break; printf("%c", ch);
}
[解答例 ]:while文(反復条件)
while( (fscanf(fp, "%c", &ch))!=EOF ) printf("%c", ch);
[解答例 ]:while文(反復条件),教p.303 while( (ch=fgetc(fp))!=EOF ) putchar(ch);
問題 .
// 演習(3-5) ファイル 問題
#include<stdio.h>
#include<stdlib.h> //exit(1);用
int main(void){ FILE *fp1, *fp2; char ch;
printf("test454.txtファイル 複製し 。\n"); if( (fp1=fopen("test454.txt","r")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
if( (fp2=fopen("copy_test454.txt","w")) == NULL){ printf("ファイル 開け し 。\n"); exit(1); //return 1; も可
}
for(;;){ //①
if( (fscanf(fp1,"%c", &ch))==EOF ) break; //①
fprintf(fp2,"%c", ch); //①
} //①
fclose(fp2); fclose(fp1);
printf("copy_test454.txt 作成し し 。\n"); return 0;
}
別解 ※上記① 部分 次 い か 解答例に置き換え も良い。
[解答例 ]:while文(反復条件)
while( (fscanf(fp1, "%c", &ch))!=EOF ) fprintf(fp2, "%c", ch);
[解答例 ]:while文(反復条件),教p.303
while( (ch=fgetc(fp1)) != EOF ) fputc(ch, fp2);