Skip to content

Instantly share code, notes, and snippets.

@ammarfaizi2
Created September 19, 2023 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ammarfaizi2/bad6a6407d125c2d335d6222c92edc52 to your computer and use it in GitHub Desktop.
Save ammarfaizi2/bad6a6407d125c2d335d6222c92edc52 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
static const char store_file[] = "./todo_data.bin";
static const char store_file_tmp[] = "./todo_data.bin.tmp";
struct todo {
char data[255];
};
static int menu(void)
{
int ret, n;
// printf("\ec");
printf("---- Welcome to the TODO List program ----\n");
printf("1. Add.\n");
printf("2. Update.\n");
printf("3. Delete\n");
printf("4. Show\n");
printf("5. Exit\n");
printf("======================================\n");
printf("Enter the option: ");
ret = scanf("%d", &n);
if (ret != 1) {
return -1;
}
while (getchar() != '\n') {
// Do nothing.
}
return n;
}
static int handle_add(FILE *h)
{
struct todo d;
memset(&d, 0, sizeof(d));
printf("Enter the todo list: ");
if (!fgets(d.data, sizeof(d.data), stdin)) {
return -1;
}
fwrite(&d, sizeof(d), 1, h);
return 0;
}
static unsigned show_todo_list(FILE *h)
{
struct todo d;
size_t ret;
unsigned i;
rewind(h);
printf("========================================\n");
printf("TODO List:\n");
i = 0;
while (1) {
ret = fread(&d, sizeof(d), 1, h);
if (ret == 0) {
break;
}
printf(" %u. %s\n", ++i, d.data);
}
printf("========================================\n");
return i;
}
static int handle_show(FILE *h)
{
show_todo_list(h);
printf("Press enter to continue!");
getchar();
return 0;
}
static int handle_delete(FILE *h)
{
unsigned n, i, choice;
FILE *th;
int ret;
n = show_todo_list(h);
printf("Which list do you want to delete? Enter the num: ");
ret = scanf("%u", &choice);
if (ret != 1) {
return -1;
}
if (choice == 0 || choice > n) {
printf("Invalid number!\n");
return 0;
}
th = fopen(store_file_tmp, "wb");
if (!th) {
perror("Failed to open the store_file_tmp");
return -1;
}
rewind(h);
for (i = 1; i <= n; i++) {
struct todo d;
fread(&d, sizeof(d), 1, h);
if (i == choice) {
continue;
}
fwrite(&d, sizeof(d), 1, th);
}
fclose(th);
remove(store_file);
rename(store_file_tmp, store_file);
return 0;
}
static int handle_input_menu(int n, FILE *h)
{
switch (n) {
case 1:
return handle_add(h);
// case 2:
// return handle_update();
case 3:
return handle_delete(h);
case 4:
return handle_show(h);
case 5:
/* For exit. */
return 1;
default:
printf("Invalid menu %d\n", n);
break;
}
return 0;
}
int main(void)
{
int ret, n;
FILE *h;
do {
h = fopen(store_file, "ab+");
if (!h) {
perror("Failed to open the store_file");
return 1;
}
n = menu();
ret = handle_input_menu(n, h);
if (ret != 0) {
break;
}
fclose(h);
} while (n != -1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment