C密码数据库

时间:2019-01-09 18:16:49

标签: c database file passwords fstream

我创建了一个程序,如果您输入文件中的先前密码,就可以从文件中更改密码。我想要做的就是能够创建一个分配了密码的用户名。用户名和密码应该写在文件中而不删除以前的任何内容。该程序还应该能够验证文件中用户名的密码。这是我当前的代码,但是我无法写给定文件中有很多东西。我不希望您给我问题的代码,只给我一些提示的算法。谢谢!

#include<stdio.h>
#include <conio.h>
#include <fstream>
#include <string.h>
#include <stdlib.h>     
int main()
{
    FILE *passwords;
    int p='*',i,j,count,triesLeft,a,numberofTries=0;
    char password[5] = {0,0,0,0,0};
    char passwordCheck[5] = {0,0,0,0,0};
    passwords = fopen("passwords.txt","r"); 
    printf("You have 3 tries to enter your password!\n");
    for(count=0;count<3;count++) 
        {
            numberofTries++;
            triesLeft = 3 - count;
            printf("You have %d tries left!\n", triesLeft);
            printf("Enter your password: ");
            scanf("%s", &passwordCheck);
            fscanf(passwords,"%s",&password);
            if(strcmp(password, passwordCheck) == 0)
                {
                    numberofTries--;
                    printf("Press 0 if you want to set up a new password, press 1 to stop the program\n");
                    scanf("%d", &a);
                    if(a==0)
                        {
                            passwords = fopen("passwords.txt","w");
                            printf("New password:");
                            for(i=0;i<5;i++)
                                {
                                    password[i] = getch();
                                    putchar(p); 
                                }
                            for(j=0;j<5;j++)
                                {
                                    fprintf(passwords,"%c",password[j]); 
                                }
                        }
                    else if(a==1)
                        {
                            printf("Old password still in place");
                        }
                    break;
                }
            else
                {
                    printf("Wrong password!");  
                }
        }
    if(numberofTries == 3)
        {
            printf("You are out tries!");
        }
    fclose(passwords); 
}

1 个答案:

答案 0 :(得分:0)

看看fopen documentation。这里的魔术短语是“访问模式”。当您打开文件时,FILE指针指向文件内部的某个位置。通过设置适当的访问模式,您可以选择打开文件时位置指针的放置位置。函数fseek也许对您也很有趣。它允许您移动该指针。

您的代码的其他提示:

  • 请确保您不要使用许多不必要的变量,因为 它们会使您的代码混乱。
  • 使用fopen时,请始终检查指针设置是否正确 (检查是否为NULL),否则您的程序可能会因 如果无法找到或访问文件,则会出现分段错误。
  • 在C中,所有不同于0或NULL的值都是正确的。那适用于 指针作为数值。随意使用否定 运算符“!”结合这些测试。