#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define INPUT_BUFFER_SIZE 256
char* password = "iamapassword";
static void print_file_contents(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "Error: could not open %s\n", filename);
return;
}
char buffer[1024];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
fwrite(buffer, 1, bytes_read, stdout);
}
fclose(fp);
}
static int password1trial() {
char input[INPUT_BUFFER_SIZE];
/* ---------- Stage 1: static password ---------- */
printf("Enter password 1: ");
if (fgets(input, sizeof(input), stdin) == NULL) {
fprintf(stderr, "Failed to read input.\n");
return 1;
}
int len = strlen(input);
if (len > 0 && input[len - 1] == '\n') {
input[len - 1] = '\0';
}
if (strcmp(input, password) != 0) {
printf("Incorrect password 1.\n");
return 1;
}
printf("Password 1 correct!\n\n");
print_file_contents("code1.txt");
printf("\n");
return 0;
}
static int password2trial() {
char input[INPUT_BUFFER_SIZE];
/* ---------- Stage 2: random password, computed before prompting ---------- */
srand((unsigned int)time(NULL));
int password2 = (rand() % 1000000) + 1; /* random number in [1, 1000000] */
printf("Enter password 2: ");
if (fgets(input, sizeof(input), stdin) == NULL) {
fprintf(stderr, "Failed to read input.\n");
return 1;
}
int guess = atoi(input);
if (guess != password2) {
printf("Incorrect password 2.\n");
return 1;
}
printf("Password 2 correct!\n\n");
print_file_contents("code2.txt");
printf("\n");
return 0;
}
int main(void) {
if(password1trial()) return 1;
if(password2trial()) return 1;
return 0;
}6 views