In: Computer Science
Hi, I am wondering how to create code that will allow (in c) the console to read a password from a .txt file, and have the ability to change this password?
I have a function that logs certain users in using simple if statements and hardcoded passwords, but i would like the ability to be able to change the password and read it from a .txt so it is editable instead of having it in a function in the code.
Thanks
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char login_pass[20];
char login_user[20];
char stored_pass[20];
char stored_user[20];
FILE *fptr;
if ((fptr = fopen("credentials.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file doesn't exist.
return -1;
}
printf("Username: ");
scanf("%s", &login_user);
while(strcmp(login_user, stored_user)){
//if login and stored username are equal, function strcmp
returns 0,
//at first loop there are not equal, as the stored_user is empty,
so the condition will be true.
fscanf(fptr,"%s", &stored_user);
if(feof(fptr)){ //if it is the end of file
printf("Username does not exist.\n ");
return -1;
}
}
//now console prompts user to enter password to confirm
username
printf("Password: ");
scanf("%s", &login_pass);
//since username and password are in the same line, password next
to
//correctly entered username will be feteched and saved to
stored_pass
fscanf(fptr,"%s", &stored_pass);
//this loop will continously check, if the entered password and
stored password are same or not
int count = 3;
while(strcmp(stored_pass,login_pass)){
if(count == 1)
return -1;
else{
count--;
printf("Wrong password. Only %d attempts left. \n", count);
printf("Please, Try again:\n");
scanf("%s", &login_pass);
}
}
printf("Login successful.\n");
fclose(fptr);
return 0;
}
Credentials.txt
---------------------
abc 123xyz
cba 124578