主题:读写文件问题
hereforc
[专家分:210] 发布于 2011-06-15 15:01:00
由于对文件这块内容不是很了解
麻烦大虾帮我编写下以下两个读写文件的程序 让我参考下 谢谢:
1.编写一个程序,用来从键盘读取本班同学的期末成绩,并把成绩保存在score.txt文件中。score.txt文件内容如下:
number Chinese English C
1 87 76 67
2 67 87 65
3 76 88 87
4 46 89 88
2.编写一个程序,用来读取上题创建的score.txt数据文件,并计算其平均成绩和期末总成绩。把计算结果存在statisti.txt文件中,并输出成绩有不及格的学生的学号。其格式如下:
number Chinese English C total average
1 87 76 67 230 76.67
2 67 87 65 219 73
3 76 88 87 251 83.67
4 46 89 88 223 74.3
回复列表 (共12个回复)
11 楼
fragileeye [专家分:1990] 发布于 2011-06-16 11:02:00
T2:
[code=c]
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SUBJECT 3
#define NO_DATA 0 // 没有数据了
#define A_DATA 1 // 还有数据
typedef struct SCORE_STU
{
int num;
int chi;
int eng;
int c;
}SCORE_REC;
int Check_Data(FILE *fp_score); //判断文件中是否存在数据
void Cal_Save_Data(FILE *fp_score, FILE *fp_statistic); //用于计算并将数据存入文件
int main(int argc, char *argv[])
{
FILE *fp_score, *fp_statistic;
int result;
fp_score = fp_statistic = NULL;
if((fp_score = fopen("score.txt", "r")) == NULL) //权衡了下 还是不知道怎么安排结构好
{
fprintf(stderr, "can't open the file \"score.txt\" !");
exit(EXIT_FAILURE);
}
result = Check_Data(fp_score);
if(!result)
{
fprintf(stdout, "No data in the file score.txt !\n");
exit(EXIT_FAILURE);
}
else
{
if((fp_statistic = (fopen("statistic.txt", "w"))) == NULL)
{
fprintf(stderr, "can't open the file \"statistic.txt\"! \n");
exit(EXIT_FAILURE);
}
else
{
Cal_Save_Data(fp_score, fp_statistic);
}
}
fclose(fp_score);
fclose(fp_statistic);
return 0;
}
int Check_Data(FILE *fp_score)
{
char ch;
if((ch = fgetc(fp_score)) == EOF)
{
return NO_DATA;
}
return A_DATA;
}
void Cal_Save_Data(FILE *fp_score, FILE *fp_statistic)
{
int index, total, retn;
double aver;
SCORE_REC score_rec;
fprintf(fp_statistic, "number Chinese English C total average\n");
while(1)
{
if(!isdigit(fgetc(fp_score)))
{
continue;
}
else
{
break;
}
}
fseek(fp_score, -1L, SEEK_CUR); //回到数字部分
while(1)
{
retn = fscanf(fp_score, "%d%d%d%d\n", &score_rec.num,
&score_rec.chi, &score_rec.eng, &score_rec.c);
if(retn == EOF)
{
break;
}
else
{
total = score_rec.chi + score_rec.eng + score_rec.c;
aver = (double)total / SUBJECT;
fprintf(fp_statistic, "%-10d%-10d%-10d%-10d%-10d%-10.2lf\n",
score_rec.num, score_rec.chi, score_rec.eng, score_rec.c
, total, aver);
}
}
puts("succeed in data pumping...");
}
[/code]
出现错误或lz有更好的思路,代码请提出来。。对了,还有 输出不及格成绩的学生信息,这点就得lz自己实现了。。应该不会难吧。
12 楼
hereforc [专家分:210] 发布于 2011-06-17 13:34:00
各位大神分析的过细了哈 不过还是感谢
我来回复