Untitled

 avatar
unknown
plain_text
2 years ago
2.1 kB
6
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_PASSWORD_LENGTH 5
#define MAX_TRY 3

void option1() {
    char password[MAX_PASSWORD_LENGTH + 1];
    int i;
    srand(time(0));
    for (i = 0; i < MAX_PASSWORD_LENGTH; i++) {
        password[i] = rand() % 26 + 'a';
    }
    password[i] = '\0';
    FILE *fp = fopen("password.txt", "w");
    if (fp == NULL) {
        printf("Error opening file!\n");
        exit(1);
    }
    fprintf(fp, "%s", password);
    fclose(fp);
    printf("Password generated and written to password.txt\n");
}

void option2() {
    char password[MAX_PASSWORD_LENGTH + 1];
    int try = 0;
    FILE *fp = fopen("password.txt", "r");
    if (fp == NULL) {
        printf("Error opening file!\n");
        exit(1);
    }
    fscanf(fp, "%s", password);
    fclose(fp);
    while (try < MAX_TRY) {
        char input[MAX_PASSWORD_LENGTH + 1];
        printf("Enter password: ");
        scanf("%s", input);
        if (strcmp(input, password) == 0) {
            fp = fopen("rubrica.txt", "r");
            if (fp == NULL) {
                printf("Error opening file!\n");
                exit(1);
            }
            printf("Access granted. Reading rubrica.txt...\n");
            char c = fgetc(fp);
            while (c != EOF) {
                printf("%c", c);
                c = fgetc(fp);
            }
            fclose(fp);
            return;
        }
        printf("Wrong password. Try again.\n");
        try++;
    }
    printf("Too many tries. Deleting files...\n");
    remove("password.txt");
    remove("rubrica.txt");
}

int main() {
    int choice;
    while (1) {
        printf("Menu:\n1. Generate password\n2. Read rubrica.txt\n3. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                option1();
                break;
            case 2:
                option2();
                break;
            case 3:
                exit(0);
            default:
                printf("Invalid choice\n");
        }
    }
    return 0;
}
Editor is loading...