【在线等…!!!】用C语言写一个密码程序

要求:设置初始密码为123456;登陆成功后,要可以修改密码。并且保存到文件里。再次运行程序时,应该输入新密码。

//---------------------------------------------------------------------------

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define PFE "pas.dat" /*保存密码的文件*/
#define DEFPAS "123456" /*初始密码*/
void setpass(void)
{
FILE *fp=NULL;
char pas[20];
printf("是否设置新密码?(Y/N):");
fflush(stdin);
if (tolower(getchar())=='y') {
printf("请输入新密码:\n");
scanf("%20s",pas);
fp=fopen(PFE,"wb");
fwrite(pas,sizeof(char),strlen(pas),fp);
fclose(fp);
printf("已经设置新密码,下次请使用新密码登录\n");
}
fflush(stdin);
}
int main(void)
{
FILE *pf;

char pass[20]=DEFPAS,ch[20];
if (pf=fopen(PFE,"rb")) {
fread(pass,sizeof(char),20,pf);

fclose(pf);
}
printf("请输入密码:");
scanf("%s",ch);
if (!strcmp(ch,pass)) {
printf("登录成功\n");
setpass();
printf("欢迎使用本系统\n");
getchar();
}
else printf("密码错误,登录失败!\n");

return 0;
}
//---------------------------------------------------------------------------
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-06-14
说明,在源文件同目录下建password.txt,初始内容为123456
由于不同编译器对getch的支持不同,如果不对,把input函数换成scanf("%s",in);即可(目前可以在devc++中成功运行),具体内容按要求修改
#include <stdio.h>
#include <string.h>
#include <conio.h>
void input(char* s)
{
int c,ct=0;
while(1)
{
c=getch();
if(c=='\r')
{
printf("\n");
break;
}
putchar('*');
s[ct++]=c;
}
s[ct]=0;
}
int main()
{
FILE *fp;
char pass[100];
char in[100];
fp=fopen("password.txt","r");
fscanf(fp,"%s",pass);
fclose(fp);
while(1)
{
printf("please input password\n");
input(in);
if(strcmp(pass,in)==0)break;
}
printf("input new password\n");
scanf("%s",pass);
fp=fopen("password.txt","w");
fprintf(fp,"%s",pass);
fclose(fp);
return(0);
}
第2个回答  2010-06-14
#include<fstream> //标准文件输入输出
#include<iostream> //标准输入输出
#include<string>
using namespace std;
ifstream fin("mima.in"); //存放原密码
ofstream fout("mima.out"); //存放新密码
int main()
{
string a,b; // a为文件中的密码, b为输入的密码;
getline(fin,a); // 读入一行;
cout<<"请输入秘密:"<<endl;
getline(cin,b);
if(a==b)
{
cout<<"密码输入正确"<<endl;
cout<<"请输入新密码: "<<endl;
cin>>a;
fout<<a;
}
else cout<<"密码错误!"<<endl;
return 0;
}
相似回答