作业1:使用分文件编译,实现注册登录界面,使用已经学过的fgets,fscanf,fpritnf函数。
main.c文件
#include "log.h"
int main(int argc, const char *argv[])
{
int ch;
while(1)
{
printf(">>>>>>1.注册\n");
printf(">>>>>>2.登录\n");
printf(">>>>>>3.退出\n");
printf("---------------------");
printf("请输入你的选择:");
scanf("%d",&ch);
getchar();
switch(ch)
{
case 1:
regist();
break;
case 2:
login();
break;
case 3:
exit(EXIT_SUCCESS);
break;
}
}
return 0;
}
login.c文件
#include "log.h"
int login()
{
//将文件内的账户密码与输入的对比
user log,reg;
printf("请输入登录账户:");
fgets(log.name,sizeof(log.name),stdin);
printf("请输入登录密码:");
fgets(log.code,sizeof(log.code),stdin);
//从文件中读取注册的账户密码与登录的账户密码比对
FILE *fp = fopen("./user.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
fscanf(fp,"%s %s",reg.name,reg.code);//读取文件字
reg.name[strlen(reg.name)+1] = 0;
reg.name[strlen(reg.name)] = 10;
reg.code[strlen(reg.code)] = 10;
if(strcmp(log.name,reg.name) == 0&&
strcmp(log.code,reg.code)==0)
{
printf("恭喜您登录成功\n");
}
else
{
printf("登录失败\n");
}
}
regist.c文件
#include "log.h"
int regist()
{
//将账户密码写入user.txt文件
user reg;//定义注册结构体变量
printf("请输入注册账户:");
fgets(reg.name,sizeof(reg.name),stdin);
printf("请输入注册密码:");
fgets(reg.code,sizeof(reg.code),stdin);
FILE *fp = fopen("./user.txt","w");
if(fp == NULL)
{
perror("fopen");
return -1;
}
//使用fprintf函数将账户密码一起写入文件
fprintf(fp,"%s%s",reg.name,reg.code);
printf("注册成功\n");
fclose(fp);
return 0;
}
log.h文件
#ifndef __LOG_H__
#define __LOG_H__
#include <myhead.h>
typedef struct
{
char name[20];
char code[20];
}user;
int regist();
int login();
#endif
及一个空文件 user.txt
作业2:使用fread和fwrite拷贝文件。
#include <myhead.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./1.txt","r");
FILE *fp1 = fopen("./2.txt","w");
if(fp==NULL)
{
perror("fopen");
return -1;
}
char s[100];
fread(s,sizeof(s),1,fp);
fwrite(s,strlen(s)-1,1,fp1);
fclose(fp);
fclose(fp1);
return 0;
}
标签:fp,code,name,作业,8.21,printf,今日,reg,log
From: https://blog.csdn.net/qq_62099195/article/details/141400351