1.字符方式读写函数fgetc( )和fputc( )
逐个字符读写函数,fgetc函数实现从fp所指式的磁盘文件读入一个字符待ch。
函数调用格式:
ch=fgetc(fp);
//该函数的功能于getchar()函数功能相似,从键盘上读取一个字符;
fgetc函数实现把一个字符ch写到fp所指示的磁盘文件上。
函数调用格式:
fputc(ch,fp);
//函数返回值若写文件成功为ch,写失败则为EOF。
//该函数和putchar()功能相似,putchar把ch显示在屏幕上。
//EOF是乘凉,其值为-1。
//文件读入读出
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
long num;
char stname[20];
int i,score;
int avg_score=0;
//读入文件
if((fp=fopen("地址""r"))==NULL)
{
printf("File open error!\n");
exit(0);
}
for(i=0;i<5;i++)
{
//读取每一行的数据,按照长整型,字符型,整型来输出
fcanf(fp,"%ld%s%d",&num,stname,&score);
avg_score+=score;
printf("%ld%s%d\n",num,stname,score);
}
printf("Average score:%d\n,avg_score/5");
//关闭文件,养成好习惯
if(fclose(fp)){
prinf("Can not close the file!\n");
exit(0);
}
return 0;
}
//以字符型式读入读出文件,实现信息加密
#include<stido.h>
#include<string.h>
#include<stdlib.h>
struct sysuser{
char uername [20];
char password [8];
};
void encrypt (char *pwd);
int main()
{
FIlE *fp;
int i;
struct sysuser su;
//打开文件
if((fp=fopen("文件名.txt","w"))==NULL){//"w"建立新文件进行只写
printf("error!\n");
exit(0);
}
for(i=1;i<=5;i++)
{
printf("enter %d name password:",i);
scanf("%s%s",su.uername,su.password); //输入账号密码
encrypt(su.uername); //加密处理
fprintf(fp,"%s%s\n",su.uername,su.password); //写入文件
}
//关闭文件
if(fclose(fp)){
printf("error\n");
exit(0);
}
return 0;
}
void encrypt(char *pwd)
{
int i;
//与15(二进制00001111)异或,实现低四位取反,高四位保持不变。
for(i=0;i<strlen(pwd);i++)
pwd[i]=pwd[i]~15;
}
本文详细介绍C语言中文件操作的基础知识,包括使用fgetc()和fputc()函数进行字符级别的读写,以及如何通过fscanf()和fprintf()处理结构化数据。此外,还介绍了如何利用字符操作实现简单的信息加密过程。
1257

被折叠的 条评论
为什么被折叠?



