// 例題4.1 score.c:成績処理 #include #include // エラーメッセージを標準エラーに出力するマクロ #define errout(s) fprintf(stderr,s) // 選手1人分のデータ struct person { char firstname[20]; char lastname[20]; int score[2]; float ratio; }; // 1人分データ読み込み // 引数 *sp:結果を格納する領域 // 戻り値 ファイル終了ならEOF int read_person(struct person *sp,FILE *ifp) { int r; r = fscanf(ifp, "%s %s %d %d", sp->firstname, sp->lastname, &(sp->score[0]), &(sp->score[1])); sp->ratio = (float)sp->score[1]/sp->score[0]; return r; } // 1人分データ書き出し // 引数 *sp:出力データ // 戻り値: 成功すれば0 int write_person(struct person *sp, FILE *ofp) { int r; r = fprintf(ofp, "%-20s%-20s%6d%6d%10.3f\n", sp->firstname, sp->lastname, sp->score[0], sp->score[1], sp->ratio); return r; } // メインプログラム int main() { FILE *ifp, *ofp; int cnt = 0; int sum[2] = {0, 0}; float ave[2]; float averatio; struct person s; // 前処理 ifp = fopen("infile" ,"r"); if (ifp==0) { errout("infile:cannot open\n"); exit(1); } ofp = fopen("outfile","w"); if (ofp==0) { errout("outfile:cannot open\n"); exit(1); } // 入力を読みながら合計に加算 while (read_person(&s,ifp) != EOF) { sum[0] += s.score[0]; sum[1] += s.score[1]; cnt ++; write_person(&s,ofp); } // 平均を求める ave[0] = (float)sum[0]/cnt; ave[1] = (float)sum[1]/cnt; averatio = (float)sum[1]/sum[0]; fprintf(ofp, "%-20s%-20s %6.3f%6.3f%6.3f\n", "Average", "", ave[0], ave[1], averatio); // 後処理 fclose(ifp); fclose(ofp); return 0; }