C語言利用連結串列與檔案實現登入註冊
阿新 • • 發佈:2018-11-09
C語言實現簡登入和註冊功能
C語言實現註冊登入
使用連結串列
使用檔案
版本二:利用連結串列
此版本使用的連結串列,第一個版本使用的是陣列
陣列版本連線
這裡我使用的線性連結串列,一定要注意在判斷語句或賦值語句中不可將指標指向未定義的區域,這會產生很大問題,所以一般都需要在連結串列最後一個節點指向空指標
#程式碼
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> typedef struct LNode { char name[10]; char pass[10]; struct Node *next; } LNode,*pNode; //定義節點 pNode createList() { pNode pHead = (pNode)malloc(sizeof(LNode)); pHead->next=NULL; //頭結點不存放資料 FILE *fp = fopen("user.txt","r"); if(NULL == fp) { printf("FILE NOT FOUND"); exit(-1); } pNode cur = pHead; while(1) { pNode temp = (pNode)malloc(sizeof(LNode)); if(!temp) exit(-1); //檢測到錄入完畢後將分配的空間清除掉 if(2!=fscanf(fp,"%s%s",temp->name,temp->pass)) { free(temp); break; } cur->next=temp; cur = temp; //使最後一個節點指向空,方便以後判斷 cur->next = NULL; } return pHead; } //登入函式 int login(pNode head) { if(NULL==head->next) { printf("user list empty\n"); getch(); return 0; } char name[10]; char pass[10]; printf("enter your name:"); scanf("%s",name); printf("enter your password:"); scanf("%s",pass); pNode temp = head->next; while(temp) { if(0==strcmp(temp->name,name) && 0==strcmp(temp->pass,pass)) { printf("success"); getch(); return 1; } temp = temp->next; } printf("user not found"); getch(); } //寫入txt檔案,每一行存在一個使用者 void writeToFile(pNode head) { FILE *fw = fopen("user.txt","a+"); pNode temp=head->next; if(temp==NULL){ return; } while(temp){ fprintf(fw,temp->name); fprintf(fw,"\t"); fprintf(fw,temp->pass); fprintf(fw,"\n"); temp = temp->next; } } //註冊使用者 void registerUser(pNode head) { pNode temp = head->next; //當表中無使用者直接在頭結點後註冊 if(!temp) { temp = (pNode)malloc(sizeof(LNode)); head->next = temp; } else { //表中有使用者則在最後一個節點後生成新節點 while(temp->next) { temp = temp->next; } pNode last = (pNode)malloc(sizeof(LNode)); temp->next = last; temp = last; } printf("enter your name:"); scanf("%s",temp->name); printf("enter your password:"); scanf("%s",temp->pass); temp->next=NULL; } int menu() { int choice; printf("1.login\n"); printf("2.register\n"); printf("#.exit\n"); printf("enter your choice:"); scanf("%d",&choice); return choice; } int main() { int choice; pNode head = createList(); while(1) { choice = menu(); if(1==choice) { system("cls"); if(login(head)) { //這裡寫登陸成功的模組 } system("cls"); } else if(2==choice) { system("cls"); registerUser(head); system("cls"); } else { writeToFile(head); return 0; } } }
##執行結果
選單,比較簡陋,可以根據自己需求加東西
這次寫了選單的迴圈
註冊
登入
異常路徑(登入失敗)