当前位置:文档之家› c语言程序设计何钦铭颜晖第12章文件

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

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);
{
char ch;
int countline=0;
FILE *fp;
if((fp=fopen("练习","r"))==NULL){
printf("Not open!");
exit(0);
}while(!feof(fp)){ ch=fgetc(fp); if(ch!=EOF) if(ch>='A'&&ch<='Z') printf("%c",ch-'A'+'a');
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",,;
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<students[i].score){
max=students[i].score;
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);
encrypt; fprintf(fp,"%s %s\n",,;
}
if(fclose(fp)){ printf("Can not close the file!\n"); exit(0);
}
return0;
}
void encrypt(char *pwd)
{
int i;
for(i=0;i<strlen(pwd);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来决定循环是否继续。

【练习 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;
else
printf("%c",ch);
if(ch=='\n') countline++;
}
printf("\n");
printf("file's line is:%d.",countline+1);
if(fclose(fp)){
printf("Can not close!");
exit(0);
}
return0;
}
【练习 12-5 】写字符并验证 : 从键盘输入一行字符,写入到文件中, 出,最终在屏幕上显示验证。程序输入以读到回车符“n”为结束, 用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);
}
return0;
}
【练习 12-2 】请使用例 8-9 答电码加密函数对民吗字符串进行加密, 改写例 12-2。 解答:
#include<>
#include<>
#include<>
struct sysuser{
char username[20];
char password[8];
};
void encrypt(char *pwd);
j=i;
}
if(min>students[i].score){
min=students[i]34;Max
score: %d,num:%d,name:%s\n",students[j].score,students[j].num,&studen ts[j].stname);
printf("f12-2中字符数量为:%d",count);
return0;
}
【练习 12-4 】字母转换并统计行数 : 读取一个指定的文本文件,显示在屏幕上, 如果有大写字母, 则改成小写字母再输出, 并根据回车符统计行数。
程序。 解答:
#include<>
#include<> int main(void)
相关主题