【例12-2】为了保障系统安全,通常采取用户账号和密码登录系统。系统用户信息存放在一个文件中,用户账号和密码由若干字母与数字字符构成,因安全需要,文件中的密码不能是明文,必须要经过加密处理。请编程实现:输入5个用户信息(包含账号和密码并写人文件 f12-2.dat。要求文件中每个用户信息占一行,账号和加密过的密码之间用一个空格分隔。密码加密算法:对每个字符ASCI码的低四位求反,高四位保持不变(即将其与 15 进行异或运算)。
#include<stdio.h> #include<string.h> #include<stdlib.h> struct sysuser{ char username[20]; char password[10]; }; void encrypt(char *pwd); int main(){ struct sysuser user; FILE *fp; if((fp=fopen("user.txt","w"))==NULL){ printf("File open error!\n"); exit(0); } int i; for(i=1;i<=5;i++){ printf("The username and password of NO.%d:",i); scanf("%s %s",user.username,user.password); encrypt(user.password); fprintf(fp,"%s %s\n",user.username,user.password); } if(fclose(fp)){ printf("Can not close the file!\n"); exit(0); } return 0; } void encrypt(char *pwd){ int i; for(i=0;i<strlen(pwd);i++){ pwd[i]=pwd[i]^15; } }输入样例:
输出结果: