8.21作业:使用fsanf和fprintf实现对user.txt文件写入和读取信息。

mymain.c

#include"log.h"
int main(int argc, const char *argv[])
{
    int ch;
    printf("1.注册\n");
    printf("2.登录\n");
    printf("3.退出\n");
    scanf("%d",&ch);
    getchar();
    switch(ch)
    {
    case 1:regist();break;
    case 2:login();break;
    case 3:exit(EXIT_SUCCESS);break;
    }
    return 0;
}
log.c

#include"log.h"
int regist()
{
    nb log;
    printf("ender make document: ");

    fgets(log.name,sizeof(log.name),stdin);
    printf("ender make code: ");
    fgets(log.code,sizeof(log.code),stdin);
    FILE *fp=fopen("./user.txt","w");
    if(fp==NULL)
    {
        printf("fopen");
        return -1;
    }
    fprintf(fp,"%s%s",log.name,log.code);
    printf("make success\n");

    fclose(fp);
    return 0;
}
reg.c

#include"log.h"
int login()
{
    nb qw,as;
    printf("ender document: ");
    fgets(qw.name,sizeof(qw.name),stdin);
    printf("ender code: ");
    fgets(qw.code,sizeof(qw.code),stdin);
    qw.name[strlen(qw.name)-1]='\0';
    qw.code[strlen(qw.code)-1]='\0';
    FILE *fp=fopen("./user.txt","r");
    if(fp==NULL)
    {
        printf("fopen");
        return -1;
    }
    fscanf(fp,"%s%s",as.name,as.code);
    printf("%s%s",as.name,as.code);
    if(strcmp(qw.name,as.name)==0&&
            strcmp(qw.code,as.code)==0)
    {
        printf("yes\n");
    }
    else
    {
        printf("no\n");
    }
}
log.h

#ifndef _LOG_H_
#define _LOG_H_
#include
typedef struct
{
    char name[20];
    char code[20];
}nb;
int regist();
int login();
#endif
 

你可能感兴趣的:(算法)