使用文件I/O實現用戶登錄系統,要求初始化註冊賬戶和密碼,再次打開顯示登錄,可以修改密碼

/*使用文件I/O實現用戶登錄系統,要求初始化註冊賬戶和密碼,再次打開顯示登錄,可以修改密碼*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

void change_word();
void sign_in();    //函數的申明

int main(int argc,char **argv)
{
    int choice;
    FILE *fd; 
    

    printf("please choice:(0)sign in :(1)change password:\n");
    scanf("%d",&choice);    //做出選擇
    
    switch(choice)    //通過switch語句做出判斷
    {
        case 0:
        sign_in();    //登錄就直接進入賬戶和密碼的輸入
        break;

        case 1:
        fd = fopen("log.txt","w+");        //選擇更改密碼就直接清空文本,再登錄
        sign_in();
        break;
    }
return 0;
}


void sign_in()
{
    int num1 = 0;
    int num2 = 0;
    char name[13];
    char pass_word[13];
    char log_name[13];
    char log_word[13];
    char buff[100];

    FILE *fd;

    fd = fopen("log.txt","r+");    //以讀寫方式打開文件

    if(fd == NULL)    
    {
        perror("fopen()");    //    判斷是否創建成功
    }

    if( getc(fd) == EOF)    //判斷文件中是否有數據,沒有就執行if語句
    {
        int n,m;

        while(getchar()!='\n');    //再每次輸入前需要清空緩衝區,不然第一個fgets會拿走前次數據

        printf("Welcome registered username:\n");
        fgets(name,13,stdin);    //從鍵盤獲取數據
        n = fputs(name,fd);    //將數據放入文本
    
        printf("Welcome the registered password:\n");
        fgets(pass_word,13,stdin);
        m = fputs(pass_word,fd);

        if(n >= 0 && m >= 0)    //判斷數據是否放入成功成功則返回非負整數
        {
            printf("log success。\n");
        }

    }

    else
    {
        int n,m;

        while(getchar()!='\n');

        printf("You have already registered,please enter your name:\n");        
        fgets(log_name,sizeof(log_name),stdin);

        printf("please enter your password:\n");
        fgets(log_word,sizeof(log_word),stdin);
    
        
        memset(buff, 0, sizeof(buff));
    

        rewind(fd);    //將文件的偏移量調整到文件開頭。

        fgets(buff,sizeof(buff),fd);
        n = strcmp(buff,log_name);    //使用strcmp函數判斷兩個字符串是否相同

        memset(buff, 0, sizeof(buff));
        
        fgets(buff,sizeof(buff),fd);
        m = strcmp(buff,log_word);
        memset(buff, 0, sizeof(buff));
       
        if(n == 0 && m == 0)
        {
            printf("log success.\n");
        }            
        else
            printf("enter error.\n");
    }

    fclose(fd);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章