2021-01-06 C语言之文件

2021.1.6 C语言之文件

  1. 文件有多种
  2. C语言中文件是一种数据组织方式,按照数据存放类型:字符流和二进制流分别称为文本文件和二进制文件
  3. 文件结构和自定义类型 typedef这个关键字可以把struct结构体重命名为FILE,来简化对复杂数据的定义
  4. 下面是一个将姓名密码输到文件夹的代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct sysueser{
	char username[20];
	char passward[8];
};
void encrypt (char *pwd);//定义加密函数 
int main (void){
	FILE*fp;
	int i;
	struct sysueser su;//结构体 
	
	if ((fp=fopen("f12-2.txt","w"))==NULL){//如果新建的文件夹找不到指针 
		printf ("FILE OPEN ERROR");
		exit(0);//退出,类似于return 0 操作 
	}
	
	for (i=1;i<=5;i++){//输入学生姓名,密码 
		printf("enter %d th sysuser(name passward):",i);
		scanf("%s%s",su.username ,su.passward );
		encrypt(su.passward );
		fprintf (fp,"%s%s\n",su.username ,su.passward );
	}
	if(fclose(fp)){
		printf("can’t close \n");
	exit(0);
	}
	return 0;
}


void encrypt (char *pwd){
	int i;
	for(i=0;i<strlen(pwd);i++)
{
	pwd[i]=pwd[i]^15;
}
}

老师写的类似改进版,多了一个 while !feof(fp)来控制

void main()
{
	FILE *fp1,*fp2;
   	char ch;

    if(( fp1 = fopen( "f2.txt", "r" )) == NULL){
        printf(" File open error!\n" );
        exit(0);
   	}

   	if(( fp2 = fopen( "f3.txt", "w" )) == NULL){
   	    printf(" File open error!\n" );
   	    exit(0);
   	}

   	while( !feof( fp1 ) )
	{
         ch = fgetc( fp1 );
         if(ch!=EOF)
			 fputc(ch, fp2);
   	}
        /*关闭文件f12-2.txt */ 
    if(fclose(fp1))
	{ 
		printf("Can not close the file!\n");
		exit(0);
	}
/*关闭文件f12-3.txt */
	if(fclose(fp2))
	{ 
		printf("Can not close the file!\n"); 
		exit(0);
	}
}
#endif

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值