指针学习二十三——文件读写函数

本文详细介绍C语言中文件操作的基础知识,包括使用fgetc()和fputc()函数进行字符级别的读写,以及如何通过fscanf()和fprintf()处理结构化数据。此外,还介绍了如何利用字符操作实现简单的信息加密过程。

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;
 		
 }

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值