【发布时间】:2019-06-04 13:55:43
【问题描述】:
我创建了一个程序,如果您输入该文件中的先前密码,您可以从该文件更改密码。我想要做的是能够创建一个分配有密码的用户名。用户名和密码应该写入文件而不删除之前的任何内容。程序还应该能够验证文件中用户名的密码。这是我当前的代码,但我无法编写给定文件中有多个内容。我不想让你给我问题的代码,只给我一些提示的算法。谢谢!
#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() 手册页,你有:“a”这个附加到一个文件。写入操作,在文件末尾追加数据。如果文件不存在,则创建该文件。"w" 创建一个用于写入的空文件。如果已存在同名文件,则删除其内容,并将该文件视为新的空文件。
标签: c database file passwords fstream