C 密码数据库

标签 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); 
}

最佳答案

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

有关代码的更多提示:

  • 确保您不会使用许多不必要的变量,因为 它们会让你的代码变得困惑。
  • 使用fopen时,请务必检查指针设置是否正确 (检查 NULL),否则你的程序可能会崩溃 如果无法找到或访问文件,则出现段错误。
  • 在 C 中,所有不同于 0 或 NULL 的内容都是 true。这适用于 指针与数值一样。随意使用否定 运算符(operator) ”!”与此类测试相结合。

关于C 密码数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116105/

相关文章:

java - 如何在数据库中生成序号序列?

c - 如何在 C 项目中组织/简化文件 main.c

file - React-Native - 本地文件的路径

c - 内存分配与数组大小定义

c - 如何删除C中字符串中的空格?

java - Solr 日期范围存储帮助

python - 将一个文件的代码应用到多个文件python(新手问题)

c - 为什么通过scanf()输入一个非预期的值类型会导致这个程序进入死循环

c - 如何为多线程生产者-消费者 C 程序编写测试?

php - 来自 mysql 路径和带有树形菜单的 php 的图片库