作业1:使用分文件编译,实现注册登录界面,使用已经学过的fgets,scanf,fpritnf函数。
main.c
#include "log.h"
int main(int argc, const char *argv[])
{
int ch;
while(1)
{
printf("\t\t\t1.注册\n");
printf("\t\t\t2.登录\n");
printf("\t\t\t3.退出\n");
printf("请输入>>>");
scanf("%d",&ch);
getchar();
switch(ch)
{
case 1:
regist();
break;
case 2:
login();
break;
case 3:
exit(EXIT_SUCCESS);
break;
}
}
return 0;
log.h
#ifndef _IOG_H_
#define _IOG_H_
#include <myhead.h>
typedef struct
{
char name[20];
char pwd[20];
}user;//用户结构体
int login();
int regist();
#endif
log.c
#include "log.h"
int login()
{
user log,reg;
printf("请输入登录账户:");
fgets(log.name,sizeof(log.name),stdin);
printf("请输入登录密码:");
fgets(log.pwd,sizeof(log.pwd),stdin);
FILE *fp = fopen("./user.txt","r");
if(fp == NULL)
{
perror("fopen");
return -1;
}
fscanf(fp,"%s%s",reg.name,reg.pwd);//读取文件字符串
strcat(reg.name,"\n");
strcat(reg.pwd,"\n");
printf("%s%s",reg.name,reg.pwd);//输出读取的字符串
if(strcmp(log.name,reg.name) == 0 && strcmp(log.pwd,reg.pwd) == 0)
{
printf("登录成功\n");
}
else
{
printf("登录失败\n");
}
}
reg.c
#include "log.h"
int regist()
{
//将账户密码写入user.txt文件
user reg;//定义注册结构体变量
printf("请输入注册账户:");
fgets(reg.name,sizeof(reg.name),stdin);//从键盘写入账户密码
printf("请输入注册密码:");
fgets(reg.pwd,sizeof(reg.pwd),stdin);
FILE *fp = fopen("./user.txt","w");
if(fp == NULL)
{
perror("fopen");
return -1;
}
//使用fprintf函数将账户密码一起写入文件
fprintf(fp,"%s%s",reg.name,reg.pwd);
printf("注册成功\n");
fclose(fp);//关闭文件
return 0;}
作业2:使用fread和fwrite拷贝文件。
程序代码:
#include<myhead.h>
int main(int argc, char const *argv[])
{
char t[50];
char a[50]={"wudi"};
FILE *fp=fopen("./1.txt","w+");
if(fp==NULL)
{
perror("fopen");
return -1;
}
FILE *fp2=fopen("./22.txt","w");
if(fp2==NULL)
{
perror("fopen");
return -1;
}
fwrite(&a,sizeof(a),1,fp);
fseek(fp,0,SEEK_SET);
fread(&t,sizeof(t),1,fp);
fwrite(&t,sizeof(t),1,fp2);
printf("%s\n",t);
fclose(fp);
fclose(fp2);
return 0;