C โปรเจกต์: โปรแกรม to-do แบบ CLI



สร้างโปรแกรมจัดการ to-do list ที่ใช้จากเทอร์มินัล — เก็บข้อมูลลงไฟล์ text อ่านกลับมาได้

สิ่งที่ทำได้

./todo add "ซื้อของเข้าบ้าน"
./todo add "อ่านหนังสือ C"
./todo list
./todo done 1
./todo rm 2

โครงสร้าง

todo/
├── todo.c
├── task.c
├── task.h
└── Makefile

task.h

#ifndef TASK_H
#define TASK_H

#include <stdbool.h>
#include <stddef.h>

#define MAX_TASKS 500
#define MAX_TITLE 200

typedef struct {
    int  id;
    bool done;
    char title[MAX_TITLE];
} Task;

typedef struct {
    Task   items[MAX_TASKS];
    size_t count;
    int    next_id;
} TaskList;

// คืน 0 = ok, -1 = error
int  tasklist_load(TaskList *list, const char *path);
int  tasklist_save(const TaskList *list, const char *path);
int  tasklist_add(TaskList *list, const char *title);
int  tasklist_mark_done(TaskList *list, int id);
int  tasklist_remove(TaskList *list, int id);
void tasklist_print(const TaskList *list);

// แปลงสตริงเป็น id ที่ถูกต้อง (> 0, ตัวเลขล้วน); คืน 0 = ผิดรูปแบบ
int  task_parse_id(const char *s);

#endif

task.c

#include "task.h"
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// แปลงสตริงเป็น id: ต้องเป็นตัวเลขล้วน > 0 และไม่เกินช่วง int; คืน 0 = ผิดรูปแบบ
int task_parse_id(const char *s)
{
    errno = 0;
    char *end;
    long v = strtol(s, &end, 10);
    if (end == s || *end != '\0')            return 0;   // ว่าง หรือมีขยะต่อท้าย ("1junk")
    if (errno == ERANGE || v <= 0 || v > INT_MAX) return 0;
    return (int)v;
}

int tasklist_load(TaskList *list, const char *path)
{
    list->count = 0;
    list->next_id = 1;

    FILE *f = fopen(path, "r");
    if (!f) {
        if (errno == ENOENT) {
            return 0;             // ยังไม่มีไฟล์ = ลิสต์ว่าง (ปกติตอนรันครั้งแรก)
        }
        perror(path);             // สิทธิ์ไม่พอ ฯลฯ = error จริง — อย่าถือเป็นลิสต์ว่างแล้วเขียนทับ
        return -1;
    }

    char line[MAX_TITLE + 32];
    while (list->count < MAX_TASKS && fgets(line, sizeof(line), f) != NULL) {
        // รูปแบบไฟล์: <id>\t<0|1>\t<title>
        size_t line_len = strcspn(line, "\n");
        if (line[line_len] != '\n' && !feof(f)) {
            fprintf(stderr, "%s: บรรทัดยาวเกิน — ไฟล์เสียหาย\n", path);
            fclose(f);
            return -1;            // บรรทัดถูกตัด อ่านต่อจะเพี้ยน
        }
        line[line_len] = '\0';

        char *tab1 = strchr(line, '\t');
        if (!tab1) continue;
        char *tab2 = strchr(tab1 + 1, '\t');
        if (!tab2) continue;
        *tab1 = *tab2 = '\0';

        int id = task_parse_id(line);
        if (id == 0) continue;                     // id ผิดรูปแบบ — ข้าม
        if ((tab1[1] != '0' && tab1[1] != '1') || tab1[2] != '\0') continue;  // สถานะต้องเป็น 0/1
        if (strlen(tab2 + 1) >= MAX_TITLE) continue;

        Task *t = &list->items[list->count];
        t->id = id;
        t->done = (tab1[1] == '1');
        snprintf(t->title, sizeof(t->title), "%s", tab2 + 1);

        if (t->id >= list->next_id) {
            list->next_id = (t->id < INT_MAX) ? t->id + 1 : INT_MAX;
        }
        list->count++;
    }

    if (ferror(f)) {              // fgets คืน NULL เพราะอ่านพลาด ไม่ใช่จบไฟล์
        perror(path);
        fclose(f);
        return -1;
    }
    if (list->count >= MAX_TASKS && fgets(line, sizeof(line), f) != NULL) {
        fprintf(stderr, "%s: มีมากกว่า %d รายการ — โหลดไม่ครบ ปฏิเสธเพื่อไม่ให้ save ทับข้อมูลหาย\n",
                path, MAX_TASKS);
        fclose(f);
        return -1;
    }

    fclose(f);
    return 0;
}

// เขียนไฟล์ชั่วคราวแล้ว rename ทับ — save ที่ล้มเหลวกลางคันจะไม่ทำข้อมูลเดิมหาย
int tasklist_save(const TaskList *list, const char *path)
{
    char tmp[512];
    if (snprintf(tmp, sizeof(tmp), "%s.tmp", path) >= (int)sizeof(tmp)) {
        fprintf(stderr, "path ยาวเกิน\n");
        return -1;
    }

    FILE *f = fopen(tmp, "w");
    if (!f) {
        perror(tmp);
        return -1;
    }
    for (size_t i = 0; i < list->count; i++) {
        const Task *t = &list->items[i];
        if (fprintf(f, "%d\t%d\t%s\n", t->id, t->done ? 1 : 0, t->title) < 0) {
            perror(tmp);
            fclose(f);
            remove(tmp);
            return -1;
        }
    }
    if (fclose(f) != 0) {          // fclose flush — เช็ค write error ที่นี่ด้วย
        perror(tmp);
        remove(tmp);
        return -1;
    }
    if (rename(tmp, path) != 0) {  // POSIX: atomic replace บนระบบไฟล์เดียวกัน
        perror("rename");
        remove(tmp);
        return -1;
    }
    return 0;
}

บน POSIX rename() เขียนทับไฟล์ปลายทางที่มีอยู่แบบ atomic — แต่บน Windows rename() จะล้มเหลวถ้าปลายทางมีอยู่ ต้อง remove(path) ก่อน (เสีย atomicity) หรือใช้ MoveFileEx(..., MOVEFILE_REPLACE_EXISTING)

int tasklist_add(TaskList *list, const char *title)
{
    if (list->count >= MAX_TASKS) {
        fprintf(stderr, "task เต็มแล้ว (สูงสุด %d)\n", MAX_TASKS);
        return -1;
    }
    if (list->next_id >= INT_MAX) {
        fprintf(stderr, "id หมดช่วงแล้ว\n");
        return -1;
    }
    if (title == NULL || title[0] == '\0') {
        fprintf(stderr, "ต้องระบุชื่อ task\n");
        return -1;
    }
    if (strlen(title) >= MAX_TITLE) {                // limit เป็น "ไบต์" ไม่ใช่จำนวนอักษร
        fprintf(stderr, "ชื่อ task ยาวเกิน %d ไบต์\n", MAX_TITLE - 1);
        return -1;
    }
    if (strpbrk(title, "\t\n\r") != NULL) {          // กันตัวคั่น/ขึ้นบรรทัดที่ทำ format ไฟล์พัง
        fprintf(stderr, "ชื่อ task ห้ามมี tab หรือขึ้นบรรทัดใหม่\n");
        return -1;
    }

    Task *t = &list->items[list->count];
    t->id = list->next_id++;
    t->done = false;
    snprintf(t->title, sizeof(t->title), "%s", title);
    list->count++;
    return 0;
}

static Task *find_by_id(TaskList *list, int id)
{
    for (size_t i = 0; i < list->count; i++) {
        if (list->items[i].id == id) {
            return &list->items[i];
        }
    }
    return NULL;
}

int tasklist_mark_done(TaskList *list, int id)
{
    Task *t = find_by_id(list, id);
    if (!t) {
        fprintf(stderr, "ไม่พบ task #%d\n", id);
        return -1;
    }
    t->done = true;
    return 0;
}

int tasklist_remove(TaskList *list, int id)
{
    for (size_t i = 0; i < list->count; i++) {
        if (list->items[i].id == id) {
            // เลื่อนตัวหลังมาแทน
            for (size_t j = i; j + 1 < list->count; j++) {
                list->items[j] = list->items[j + 1];
            }
            list->count--;
            return 0;
        }
    }
    fprintf(stderr, "ไม่พบ task #%d\n", id);
    return -1;
}

void tasklist_print(const TaskList *list)
{
    if (list->count == 0) {
        printf("ยังไม่มี task\n");
        return;
    }
    for (size_t i = 0; i < list->count; i++) {
        const Task *t = &list->items[i];
        printf("[%c] %3d  %s\n", t->done ? 'x' : ' ', t->id, t->title);
    }
    printf("\nรวม %zu task\n", list->count);
}

todo.c

#include "task.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DB_PATH "todo.txt"

static void usage(const char *prog)
{
    fprintf(stderr,
        "ใช้งาน:\n"
        "  %s add <ชื่อ task>\n"
        "  %s list\n"
        "  %s done <id>\n"
        "  %s rm <id>\n",
        prog, prog, prog, prog);
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        usage(argv[0]);
        return 2;
    }

    TaskList list;
    if (tasklist_load(&list, DB_PATH) != 0) {
        return 1;
    }

    const char *cmd = argv[1];
    int rc = 0;

    if (strcmp(cmd, "list") == 0) {
        tasklist_print(&list);

    } else if (strcmp(cmd, "add") == 0) {
        if (argc < 3) { usage(argv[0]); return 2; }
        rc = tasklist_add(&list, argv[2]);
        if (rc == 0) rc = tasklist_save(&list, DB_PATH);
        if (rc == 0) printf("เพิ่มแล้ว: %s\n", argv[2]);

    } else if (strcmp(cmd, "done") == 0 || strcmp(cmd, "rm") == 0) {
        if (argc < 3) { usage(argv[0]); return 2; }
        int id = task_parse_id(argv[2]);
        if (id == 0) {
            fprintf(stderr, "id ไม่ถูกต้อง: %s\n", argv[2]);
            return 2;
        }
        if (cmd[0] == 'd') {
            rc = tasklist_mark_done(&list, id);
            if (rc == 0) rc = tasklist_save(&list, DB_PATH);
            if (rc == 0) printf("ทำเครื่องหมายเสร็จ: #%d\n", id);
        } else {
            rc = tasklist_remove(&list, id);
            if (rc == 0) rc = tasklist_save(&list, DB_PATH);
            if (rc == 0) printf("ลบแล้ว: #%d\n", id);
        }

    } else {
        fprintf(stderr, "ไม่รู้จักคำสั่ง: %s\n", cmd);
        usage(argv[0]);
        return 2;
    }

    return rc != 0 ? 1 : 0;       // 0 = ok, 1 = ทำงานล้มเหลว, 2 = ใช้คำสั่งผิด (return ตรง ๆ ข้างบน)
}

Makefile

CC = gcc
CFLAGS = -std=c17 -Wall -Wextra -g -fsanitize=address,undefined
OBJS = todo.o task.o

todo: $(OBJS)
	$(CC) $(CFLAGS) -o $@ $^

%.o: %.c task.h
	$(CC) $(CFLAGS) -c $< -o $@

.PHONY: clean reset
clean:                  # ลบเฉพาะไฟล์ที่ build ขึ้นมา
	rm -f todo *.o

reset:                  # ลบฐานข้อมูลงานด้วย — แยกจาก clean โดยตั้งใจ
	rm -f todo.txt todo.txt.tmp

อย่าให้ clean ลบ todo.txt — ผู้เรียนที่ทำตามนิสัย make clean && make จากบท build จะเสียรายการงานทั้งหมด แยกเป็น target reset ที่ชื่อบอกชัดว่าลบข้อมูล

รัน

make
./todo add "ซื้อของเข้าบ้าน"
./todo add "อ่านหนังสือ C บทที่ 39"
./todo list
[ ]   1  ซื้อของเข้าบ้าน
[ ]   2  อ่านหนังสือ C บทที่ 39

รวม 2 task
./todo done 1
./todo list
[x]   1  ซื้อของเข้าบ้าน
[ ]   2  อ่านหนังสือ C บทที่ 39

รวม 2 task

ดูไฟล์ todo.txt:

1	1	ซื้อของเข้าบ้าน
2	0	อ่านหนังสือ C บทที่ 39

จุดที่ใช้ความรู้จากบทก่อน

ส่วนบท
struct Task, struct TaskList17
argc/argv, exit code, stderr24
fopen/fgets/fprintf, strcspn22
แยกไฟล์ .h/.c, static helper26
Makefile + sanitizer27, 15
snprintf ปลอดภัย, ไม่ strcpy38
return code เป็นแบบแผน32

ต่อยอด

  • แยก field ด้วย format แข็งแรงกว่า — if (sscanf(line, "%d\t%d\t%199[^\n]", &id, &done, title) == 3) { ... } ต้องจำกัดความกว้าง (%199 สำหรับ title[200] — ไม่งั้นเขียนเกิน buffer) และเช็คว่าได้ครบ 3 field
  • dynamic array แทน Task items[500] — ไม่จำกัดจำนวน (โปรเจกต์ที่ 40)
  • todo edit <id> <ชื่อใหม่>, todo clear (ลบที่ done แล้ว)
  • path ของ DB จาก env — getenv("TODO_FILE") fallback เป็น ~/.todo.txt
  • เทสต์ — task.c แยกจาก I/O แล้ว ทดสอบ tasklist_add/remove/mark_done ด้วย test runner (บทที่ 34)

เรื่องที่คนมักพลาด

  • ไม่ save หลังแก้ — add/done/rm ต้อง tasklist_save ต่อ ไม่งั้นไฟล์ไม่อัปเดต
  • atoi(argv[2]) — done 1junk ได้ 1, argument ว่างได้ 0 ใช้ strtol ตรวจ end pointer + ช่วง (task_parse_id)
  • title มี \t หรือ \n — ทำ format ไฟล์พัง; ปฏิเสธตั้งแต่ tasklist_add (strpbrk) ไม่ใช่แค่เตือนท้ายบท
  • ชื่อยาวเกิน limit แล้ว snprintf ตัดเงียบ ๆ — ข้อความ success ยังพิมพ์ชื่อเต็ม ปฏิเสธไปเลยดีกว่า; limit นับเป็น ไบต์ ไม่ใช่จำนวนอักษรไทย
  • save ด้วย "w" ตรง ๆ แล้วล้มเหลวกลางคัน — ข้อมูลเดิมหาย เขียน .tmp แล้ว rename (atomic) + เช็ค fprintf ทุกครั้ง ไม่พึ่ง fclose จุดเดียว
  • ไฟล์เกิน MAX_TASKS — load หยุดแล้วคืน success คำสั่ง save จะตัดส่วนเกินทิ้ง ต้องตรวจว่ายังมีข้อมูลเหลือแล้วปฏิเสธ
  • t->id + 1 เมื่อ id เป็น INT_MAX — overflow (UB) cap next_id ไว้ที่ INT_MAX และเช็คใน tasklist_add
  • fopen ล้มเหลว = ลิสต์ว่างทุกกรณี — สิทธิ์ไม่พอ/ดิสก์พังก็กลายเป็นว่างแล้ว save ทับ รับเฉพาะ errno == ENOENT
  • ไม่เช็ค ferror() หลัง fgets / บรรทัดยาวเกิน buffer — อ่านพังหรือถูกตัดกลางบรรทัดก็ดูเหมือนจบไฟล์ปกติ

สรุป

  • โปรแกรม CLI: argv[1] = คำสั่งย่อย, argv[2..] = argument, exit code บอกผล
  • โหลดไฟล์ตอนเริ่ม → แก้ในหน่วยความจำ → save หลังทุกคำสั่งที่เปลี่ยนข้อมูล
  • load แยก “ไม่มีไฟล์” (ENOENT = ว่าง, ปกติ) ออกจาก error จริง และเช็ค ferror() ก่อนถือว่าอ่านสำเร็จ
  • แยก task.c (logic + I/O ของ TaskList) ออกจาก todo.c (จัดการ argv) — ทดสอบ logic ได้
  • format ไฟล์แบบ tab-separated อ่านง่ายทั้งคนและโปรแกรม; validate ทุก field ตอนโหลด (id, สถานะ 0/1, ความยาว title)
  • save = เขียน .tmp → rename (atomic) + เช็ค fprintf/fclose — save ที่พังไม่ทำข้อมูลเดิมหาย
  • exit code: 0 ok, 1 ทำงานล้มเหลว, 2 ใช้คำสั่งผิด — ใช้แบบแผนเดียวทั้งโปรแกรม
  • ทุกฟังก์ชันคืน 0/-1, พิมพ์ error ไป stderr

บทถัดไป โปรเจกต์สร้าง dynamic array (vector) — API malloc/realloc/free ที่สะอาดและทดสอบได้