Lesson 4 of 8
CLI Parsing & Main Dispatch
The `main.c` ties the project together: `getopt_long` parses the subcommand (add/list/done/delete/stats) and its options, loads the database, performs the operation, saves back if needed, and uses `goto cleanup` for guaranteed resource release. This is the production pattern.
main.c - Subcommand Dispatch with Cleanup Pattern
/* main.c - entry point and command dispatch */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <time.h>
#include "task.h"
#include "store.h"
static void usage(const char *prog) {
printf("Usage: %s <command> [options]
"
"Commands:
"
" add "title" [--priority=low|medium|high]
"
" list [--status=pending|done|all]
"
" done <id>
"
" delete <id>
"
" stats
"
" help
", prog);
}
static int cmd_add(int argc, char **argv, TaskList *tl) {
const char *title = NULL;
Priority prio = PRIO_MEDIUM;
struct option opts[] = {
{"priority", required_argument, NULL, 'p'},
{NULL, 0, NULL, 0}
};
int opt;
while ((opt = getopt_long(argc, argv, "p:", opts, NULL)) != -1) {
if (opt == 'p') {
if (strcmp(optarg, "high") == 0) prio = PRIO_HIGH;
else if (strcmp(optarg, "low") == 0) prio = PRIO_LOW;
else if (strcmp(optarg, "medium") == 0) prio = PRIO_MEDIUM;
else { fprintf(stderr, "Unknown priority: %s
", optarg); return 1; }
}
}
if (optind >= argc) { fprintf(stderr, "add: missing title
"); return 1; }
title = argv[optind];
Task t = task_create(title, prio, 0);
t.id = task_next_id(tl);
if (tasklist_push(tl, &t) != 0) return 1;
printf("Added task #%u: "%s" [%s]
", t.id, t.title, task_prio_str(prio));
return 0;
}
static int cmd_list(const TaskList *tl) {
int shown = 0;
printf("%-4s %-40s %-11s %s
", "ID", "Title", "Status", "Priority");
printf("%-4s %-40s %-11s %s
", "----", "----", "------", "--------");
for (size_t i = 0; i < tl->size; i++) {
const Task *t = &tl->data[i];
if (t->status == STATUS_DELETED) continue;
printf("%-4u %-40s %-11s %s
",
t->id, t->title,
task_status_str(t->status),
task_prio_str(t->priority));
shown++;
}
printf("(%d tasks)
", shown);
return 0;
}
static int cmd_done(const char *id_str, TaskList *tl) {
uint32_t id = (uint32_t)atoi(id_str);
Task *t = tasklist_find_by_id(tl, id);
if (!t) { fprintf(stderr, "Task %u not found
", id); return 1; }
t->status = STATUS_DONE;
printf("Task #%u marked done
", id);
return 0;
}
static int cmd_delete(const char *id_str, TaskList *tl) {
uint32_t id = (uint32_t)atoi(id_str);
Task *t = tasklist_find_by_id(tl, id);
if (!t) { fprintf(stderr, "Task %u not found
", id); return 1; }
t->status = STATUS_DELETED;
printf("Task #%u deleted
", id);
return 0;
}
static int cmd_stats(const TaskList *tl) {
int pending=0, in_prog=0, done=0;
for (size_t i = 0; i < tl->size; i++) {
switch (tl->data[i].status) {
case STATUS_PENDING: pending++; break;
case STATUS_IN_PROGRESS: in_prog++; break;
case STATUS_DONE: done++; break;
default: break;
}
}
printf("Total: %zu
", tl->size);
printf("Pending: %d
", pending);
printf("In Progress: %d
", in_prog);
printf("Done: %d
", done);
return 0;
}
int main(int argc, char **argv) {
if (argc < 2) { usage(argv[0]); return 1; }
const char *db_path = getenv("TASKMAN_DB");
if (!db_path) db_path = DEFAULT_DB;
TaskList tl;
int rc = 1;
int modified = 0;
tasklist_init(&tl);
if (store_load(db_path, &tl) != 0) goto cleanup;
const char *cmd = argv[1];
/* shift argv so getopt in sub-commands sees the right args */
argv[1] = argv[0];
argv++;
argc--;
if (strcmp(cmd, "add") == 0) { rc = cmd_add(argc, argv, &tl); modified = 1; }
else if (strcmp(cmd, "list") == 0) { rc = cmd_list(&tl); }
else if (strcmp(cmd, "done") == 0 && argc > 1) { rc = cmd_done(argv[1], &tl); modified = 1; }
else if (strcmp(cmd, "delete") == 0 && argc > 1) { rc = cmd_delete(argv[1], &tl); modified = 1; }
else if (strcmp(cmd, "stats") == 0) { rc = cmd_stats(&tl); }
else if (strcmp(cmd, "help") == 0) { usage(argv[-1]); rc = 0; }
else { fprintf(stderr, "Unknown command: %s
", cmd); usage(argv[-1]); }
if (modified && rc == 0) {
if (store_save(db_path, &tl) != 0) rc = 1;
}
cleanup:
tasklist_free(&tl);
return rc;
}Common Mistakes
- Only saving after successful commands - notice `if (modified && rc == 0)`. If the command fails partway through (e.g., push fails), we don't save the corrupted state.
- Not shifting argv for subcommand getopt - `getopt` uses the global `optind` starting at 1. After identifying the subcommand as `argv[1]`, shift so `argv[0]` is the subcommand name and `argc/argv` reflect only the sub-command's arguments.
- Not resetting `optind` between calls - if you call `getopt_long` multiple times (rare), `optind` must be reset to `1` before the second call. The shift-argv approach avoids this entirely.
Tip
Tip
Practice CLI Parsing Main Dispatch in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Command dispatcher parses interactive commands (SET, GET, DEL, DUMP) and invokes handlers
Practice Task
Note
Practice Task - (1) Write a working example of CLI Parsing Main Dispatch from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with CLI Parsing Main Dispatch is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- Only saving after successful commands - notice `if (modified && rc == 0)`. If the command fails partway through (e.g., push fails), we don't save the corrupted state.
- Not shifting argv for subcommand getopt - `getopt` uses the global `optind` starting at 1. After identifying the subcommand as `argv[1]`, shift so `argv[0]` is the subcommand name and `argc/argv` reflect only the sub-command's arguments.
- Not resetting `optind` between calls - if you call `getopt_long` multiple times (rare), `optind` must be reset to `1` before the second call. The shift-argv approach avoids this entirely.
Finished this lesson?