第 12 章 文件
【练习 12-1 】读出例 12-1 学生成绩文件 f12-1.txt 内容,输出最高分和最低分
及相应的学号和姓名。
解答:
#include
#include
struct student{
long num;
char stname[20];
int score;
};
int main(void)
{
FILE *fp;
int i,max,min,j=0,k=0;
struct student students[5];
if((fp=fopen("f12-1.txt","r"))==NULL) {
printf("File open error!\n");
exit(0);
}
fscanf(fp,"%ld%s%d",&students[0].num,students[0].stname,&students[0]
.score);
max=min=students[0].score;
for(i=1;i<=4;i++){
fscanf(fp,"%ld%s%d",&students[i].num,students[i].stname,&students[i].
score);
if(max
max=students[i].score;
j=i;
}
if(min>students[i].score){
min=students[i].score;
k=i;
}
}
printf("Max
score: %d,num:%d,name:%s\n",students[j].score,students[j].num,&studen
ts[j].stname);
printf("Min
score: %d,num:%d,name:%s\n",students[k].score,students[k].num,&studen
ts[k].stname);
if(fclose(fp)){
printf("Can not close the file!\n");
exit(0);
}
return 0;
}
【练习12-2 】请使用例 8-9 答电码加密函数对民吗字符串进行加密, 改写例 12-2 。
解答:
#include
#include
#include
struct sysuser{
char username[20];
char password[8];
};
void encrypt(char *pwd);
int main(void)
{
FILE *fp;
int i;
struct sysuser su;
if((fp=fopen("f12-2.txt","w"))==NULL){
printf("File open error!\n");
exit(0);
}
for(i=1;i<=5;i++){
printf("Enter %dth sysuser (name password):",i);
scanf("%s%s",su.username,su.password);
encrypt(su.password);
fprintf(fp,"%s %s\n",su.username,su.password);
}
if(fclose(fp)){
printf("Can not close the file!\n");
exit(0);
}
return 0;
}
void encrypt(char *pwd)
{
int i;
for(i=0;i
if(pwd[i]=='z')
pwd[i]='