c语言程序设计何钦铭颜晖第12章文件

  • 格式:doc
  • 大小:67.50 KB
  • 文档页数:17

下载文档原格式

  / 17
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第12章文件

【练习12-1】读出例12-1学生成绩文件内容,输出最高分和最低分及相应的学号和姓名。

解答:

#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("","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("","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",,;

encrypt;

fprintf(fp,"%s %s\n",,;

}

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]='a';

else

pwd[i]+=1;

}

【练习12-3】例12-3中为什么在执行fputc(ch,fp2)前要判断ch的值是否等于EOF改写例12-3的程序,在复制用户信息文件后,再统计被复制文件中字符的数量。

解答:

文件结束符EOF是一个值为-1的常量,读文件时可用来判断从文件中读入的字符是否为EOF来决定循环是否继续。

#include<>

#include<>

int main(void)

{

FILE *fp1,*fp2;

char ch;

int count=0;

if((fp1=fopen("","r"))=NULL){

printf("File open error!\n");

exit(0);

}

if((fp2=fopen("","w"))==NULL){

printf("File open error!\n");

exit(0);

}

while(!feof(fp1)){

ch=fgetc(fp1);

if(ch!=EOF) {

fputc(ch,fp2);

count++;

}

}

if(fclose(fp1)){

printf("Can not close the file!\n");

exit(0);

}

if(fclose(fp2)){

printf("Can not close the file!\n");

exit(0);

}