C语言程序设计(第3版)何钦铭 颜 晖 第12章 文件 下载本文

内容发布更新时间 : 2024/5/4 6:46:59星期一 下面是文章的全部内容请认真阅读。

第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(\ printf(\ exit(0); }

fscanf(fp,\.score);

max=min=students[0].score; for(i=1;i<=4;i++){

fscanf(fp,\score);

if(max

if(min>students[i].score){ min=students[i].score; k=i; } }

printf(\

score: %d,num:%d,name:%s\\n\ts[j].stname); printf(\

score: %d,num:%d,name:%s\\n\ts[k].stname);

if(fclose(fp)){

printf(\ 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(\ printf(\ exit(0); }

for(i=1;i<=5;i++){

printf(\ scanf(\ encrypt(su.password);

fprintf(fp,\ }

if(fclose(fp)){

printf(\ exit(0); }

return 0; }

void encrypt(char *pwd) {

int i;

for(i=0;i

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(\ printf(\ exit(0); }

if((fp2=fopen(\ printf(\ exit(0); }

while(!feof(fp1)){ ch=fgetc(fp1); if(ch!=EOF) { fputc(ch,fp2); count++; } }

if(fclose(fp1)){

printf(\ exit(0); }

if(fclose(fp2)){

printf(\ exit(0); }