summary refs log tree commit diff stats
path: root/svc/db_test.go
Commit message (Expand)AuthorAgeFilesLines
* renamed functionsBen Morrison2019-06-061-2/+2
* fixed some import commentsBen Morrison2019-06-051-1/+1
* moved bulk of code to its own package to clean up source treeBen Morrison2019-06-051-0/+92
='n34' href='#n34'>34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124



























































































































                                                                                                      
/*
	
*/

#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>

struct account {
	int number;
	double amount;
};

struct bank_state {
	int accounts;
	double total_amount;
};

void show_main_menu(void)
{
	printf(
	"Menu:\n"
	"	1  Create Account\n"
	"	2  Check account balance\n"
	"	3  Withdraw from account\n"
	"	4  Add to account\n"
	"	5  Send money\n"
	"	6  Close account\n"
	"	7  Check bank status\n"
	"	8  Exit\n\n"
	);
}

int are_you_sure(char *prompt)
{
	char c;
	printf("%s\n", prompt);
	for (;;) {
		printf("Are you sure? (y/n): ");
		scanf("%c", &c);
		switch (c) {
		case 'y': case 'Y':
			return 1;
		case 'n': case 'N':
			return 0;
		}
		printf("Enter 'y' or 'n' to confirm your choice\n");
	}
}

int menu_prompt(int *choice)
{
	printf("Choose an option from menu: ");
	return scanf("%d", choice);
}

void discard_input_line(void)
{
	int c;
	do {
		c = getchar();
	} while (c != '\n' && c != EOF);
}

FILE *open_database(int *is_created)
{
	FILE *f;
	if (access("bank.db", F_OK) != 0) {
		// the file does not exist
		f = fopen("bank.db", "w+b");
		*is_created = 1;
	} else if (access("bank.db", R_OK | W_OK) != 0) {
		printf("Fatal error: Can not open file for reading and writing: Permission Denied\n");
		exit(65);
	} else {
		f = fopen("bank.db", "r+b");
		if (f == NULL) {
			printf("Fatal Error: Can not open bank database.\n");
			exit(64);
		}
	}
	return f;
}

void read_database(FILE *f, void **data, size_t *size)
{
	fseek(f, 0L, SEEK_END);
	*size = ftell(f);
	*data = malloc(*size);
	fread(*data, 1, *size, f);
}

void make_empty_database(FILE *f)
{
	struct bank_state st = { 0, 0.0 };
	fwrite(&st, 1, sizeof(st), f);
}

int main(void)
{
	int choice, is_created = 0;
	FILE *f;
	void *data;
	size_t size;
	f = open_database(&is_created);
	if (is_created) make_empty_database(f);
	read_database(f, &data, &size);
	printf(
	"Bank System\n"
	"===========\n\n"
	);
	for (;;) {
		show_main_menu();
		if (menu_prompt(&choice)) break;
		printf("Invalid choice. Please enter a number to choose an option from the menu.\n");
		discard_input_line();
	}
	printf("%d\n", choice);
	free(data);
	fclose(f);
	return 0;
}