1.使用fsanf和fprintf实现对user.txt文件写入和读取信息。
要求:main.c regist__login.c 主函数文件,和注册登录文件,在主函数中调用注册登录函数,注册函数对1.txt写入账户密码
登录函数读取1.txt文件内容,验证登录账户密码是否与1.txt匹配,完全匹配显示登录成功。
main.c
#include "reg.h"
int main(int argc, const char *argv[])
{
int ch;
while(1){
printf("----------------\n");
printf("1.注册\n");
printf("2.登录\n");
printf("3.退出\n");
printf("请输入你的选择:");
scanf("%d",&ch);
getchar();
switch(ch){
case 1:regist();break;
case 2:login();break;
case 3:exit(EXIT_SUCCESS);break;
default :printf("输入错误,请重新输入!\n");
}
}
return 0;
}
regist.c
#include "reg.h"
int regist(){
stu s;
printf("请输入注册账号:");
fgets(s.username,sizeof(s.username),stdin);
printf("请输入注册密码:");
fgets(s.password,sizeof(s.password),stdin);
FILE *fp = fopen("./1.txt","w");
if(fp == NULL){
perror("fopen");
return -1;
}
fprintf(fp,"%s%s",s.username,s.password);
printf("注册成功!\n");
fclose(fp);
return 0;
}
login.c
#include "reg.h"
int login(){
stu s;
printf("请输入用户账号:");
fgets(s.username,sizeof(s.username),stdin);
printf("请输入用户密码:");
fgets(s.password,sizeof(s.password),stdin);
stu t;
FILE *fp = fopen("./1.txt","r");
if(fp == NULL){
perror("fopen");
return -1;
}
fscanf(fp,"%s%s",t.username,t.password);
printf("%s\n",t.username);
printf("%s\n",t.password);
char a[10] = {'\n'};
strcat(t.username,a);
strcat(t.password,a);
if(strcmp(s.username,t.username) == 0
&& strcmp(s.password,t.password) == 0 ){
printf("登录成功!\n");
}else{
printf("密码或者账户错误!\n");
}
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/a4d8981b6d0f41499eca6da3ea5ece5f.png)
2. 使用fread和fwrite拷贝文件。
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(argc != 3){
printf("外部参数错误!\n");
return -1;
}
FILE *fp1 = fopen("./1.txt","r");
if(fp1 == NULL){
perror("fp1");
return -1;
}
FILE *fp2 = fopen("./2.txt","w");
if(fp2 == NULL){
perror("fp2");
return -1;
}
char s[100];
while(1){
fread(s,sizeof(s),1,fp1);
if(feof(fp1)){
printf("读取到文件末尾");
break;
}
if(ferror(fp1)){
printf("文件指针出错\n");
break;
}
}
fwrite(s,sizeof(s),1,fp2);
printf("复制成功!\n");
fclose(fp1);
fclose(fp2);
printf("复制后2.txt的内容:\n");
fp2 = fopen("./2.txt","r");
char r[100];
fread(r,sizeof(r),1,fp2);
printf("%s\n",r);
fclose(fp2);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/301ab5e53a5d44b39ae5d329d9597de1.png)
今日思维导图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/45729601ce584be49191993605c14638.png)