Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct userInfo
- {
- char* userName;
- char* password;
- };
- void signUp(const char* name, const char* password)
- {
- userInfo* user = getNewUser(name, password);
- FILE* file = fopen("/home/john/userinfo", "wb");
- if (!file)
- fprintf(stderr, "Error! Could not read/write file!");
- else
- fwrite(user, sizeof(userInfo), 1, file);
- fclose(file);
- }
- bool validateLogin(const char* name, const char* password)
- {
- FILE* file = fopen("/home/john/userinfo", "rb");
- if (!file)
- {
- fprintf(stderr, "Error! Could not read file.n");
- return false;
- }
- else
- {
- userInfo* user;
- while (fread(user, sizeof(userInfo), 1, file))
- {
- if ( (strcmp(name, user->userName) == 0) && (strcmp(password, user->password)== 0))
- {
- fclose(file);
- return true;
- }
- }
- }
- fclose(file);
- return false;
- }
- userInfo* getNewUser(const char* name, const char* password)
- {
- userInfo* user = malloc(sizeof(userInfo));
- user->userName = strdup(name);
- user->password = strdup(password);
- return user;
- }
- int main()
- {
- int choice = 0;
- bool quit = false;
- do
- {
- printf("Entern1. To login.n2. To sign up.nn");
- scanf("%1d", &choice);
- if (choice >= 1 && choice <= 2)
- {
- quit = true;
- if (choice == 1)
- {
- char userName[128];
- char password[128];
- flush();
- printf("nEnter username : ");
- fgets(userName, 128, stdin);
- printf("nEnter password : ");
- fgets(password, 128, stdin);
- bool isUser = validateLogin(userName, password);
- if (isUser)
- printf("nnLogin successfull!");
- else
- fprintf(stderr, "nError! Invalid username or password");
- }
- else if (choice == 2)
- {
- char userName[128];
- char password[128];
- flush();
- printf("nEnter your username : ");
- fgets(userName, 128, stdin);
- printf("Enter your password : ");
- fgets(password, 128, stdin);
- userName[strlen(userName)] = 0;
- password[strlen(password)] = 0;
- signUp(userName, password);
- printf("nnAccount created successfully!");
- }
- }
- else
- {
- fprintf(stderr, "nInvalid input! Try again.n");
- }
- }while (!quit);
- return 0;
- }
Add Comment
Please, Sign In to add comment