C โปรเจกต์: เขียน wc แบบ Unix



wc (word count) เป็นเครื่องมือ Unix คลาสสิก — นับบรรทัด คำ ไบต์ เขียนเวอร์ชันของเราเพื่อฝึกการทำ CLI ที่ทำงานกับ pipe และหลายไฟล์

เป้าหมาย

./wc file.txt
#   12   45  310 file.txt

./wc -l file.txt          # เฉพาะบรรทัด
./wc -lw *.txt            # บรรทัด + คำ, หลายไฟล์ + total
cat file.txt | ./wc       # อ่านจาก stdin
./wc < file.txt

โครงสร้าง

mywc/
├── wc.c
└── Makefile

โปรเจกต์นี้เล็กพอ ไฟล์เดียว

wc.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

typedef struct {
    long lines;
    long words;
    long bytes;
} Counts;

typedef struct {
    bool lines;
    bool words;
    bool bytes;
} Flags;

// นับจาก stream หนึ่งอัน
static Counts count_stream(FILE *f)
{
    Counts c = {0, 0, 0};
    bool in_word = false;
    int ch;

    while ((ch = getc(f)) != EOF) {   // EOF = จบไฟล์ "หรือ" อ่านพลาด — ผู้เรียกต้องเช็ค ferror()
        c.bytes++;

        if (ch == '\n') {
            c.lines++;
        }

        if (isspace(ch)) {
            in_word = false;
        } else if (!in_word) {
            in_word = true;
            c.words++;
        }
    }
    return c;
}

static void add_counts(Counts *total, const Counts *c)
{
    total->lines += c->lines;
    total->words += c->words;
    total->bytes += c->bytes;
}

// พิมพ์บรรทัดผลลัพธ์ตาม flag
static void print_counts(const Counts *c, const Flags *fl, const char *label)
{
    if (fl->lines) printf("%8ld", c->lines);
    if (fl->words) printf("%8ld", c->words);
    if (fl->bytes) printf("%8ld", c->bytes);
    if (label)     printf(" %s", label);
    printf("\n");
}

int main(int argc, char *argv[])
{
    Flags fl = {false, false, false};
    bool any_flag = false;

    // --- parse flags แบบง่าย (-l -w -c, รวมกันได้ -lw) ---
    int argi = 1;
    for (; argi < argc; argi++) {
        const char *arg = argv[argi];
        if (arg[0] != '-' || arg[1] == '\0') {
            break;                          // ไม่ใช่ flag หรือเป็น "-" (= stdin)
        }
        if (strcmp(arg, "--") == 0) {
            argi++;
            break;
        }
        for (const char *p = arg + 1; *p; p++) {
            switch (*p) {
                case 'l': fl.lines = true; any_flag = true; break;
                case 'w': fl.words = true; any_flag = true; break;
                case 'c': fl.bytes = true; any_flag = true; break;
                default:
                    fprintf(stderr, "%s: ไม่รู้จัก option -- '%c'\n", argv[0], *p);
                    fprintf(stderr, "ใช้งาน: %s [-lwc] [file...]\n", argv[0]);
                    return 2;
            }
        }
    }

    if (!any_flag) {                         // ไม่ระบุ flag = แสดงทั้งหมด (เหมือน wc จริง)
        fl.lines = fl.words = fl.bytes = true;
    }

    int rc = 0;

    if (argi >= argc) {
        // --- ไม่มีไฟล์ = อ่าน stdin ---
        Counts c = count_stream(stdin);
        print_counts(&c, &fl, NULL);
        if (ferror(stdin)) {
            fprintf(stderr, "%s: stdin: อ่านผิดพลาด\n", argv[0]);
            rc = 1;
        }
    } else {
        // --- ประมวลผลแต่ละไฟล์ ---
        Counts total = {0, 0, 0};
        int file_count = argc - argi;

        for (; argi < argc; argi++) {
            const char *path = argv[argi];
            FILE *f;

            if (strcmp(path, "-") == 0) {
                f = stdin;
            } else {
                f = fopen(path, "rb");
                if (!f) {
                    fprintf(stderr, "%s: %s: ", argv[0], path);
                    perror("");
                    rc = 1;
                    continue;
                }
            }

            Counts c = count_stream(f);
            if (ferror(f)) {
                fprintf(stderr, "%s: %s: อ่านผิดพลาด\n", argv[0], path);
                rc = 1;
            }
            print_counts(&c, &fl, path);
            add_counts(&total, &c);

            if (f != stdin) fclose(f);
        }

        if (file_count > 1) {
            print_counts(&total, &fl, "total");
        }
    }

    // เขียนผลลัพธ์ล้มเหลว (เช่น ดิสก์เต็ม, pipe ปิด) ก็ต้องคืน error
    if (fflush(stdout) != 0 || ferror(stdout)) {
        fprintf(stderr, "%s: เขียนผลลัพธ์ล้มเหลว\n", argv[0]);
        return 1;
    }
    return rc;
}

Makefile

CC = gcc
CFLAGS = -std=c17 -Wall -Wextra -g -fsanitize=address,undefined

wc: wc.c
	$(CC) $(CFLAGS) -o $@ $<

.PHONY: clean test
clean:
	rm -f wc t1.txt t2.txt mine.raw mine.txt real.txt

# เทียบผลกับ wc จริง — ใช้ไฟล์ธรรมดา (ไม่ใช้ process substitution ที่ต้องพึ่ง bash)
# awk '{$$1=$$1}' บีบช่องว่างให้เหลือช่องเดียว เพราะความกว้างคอลัมน์ของ wc จริงไม่คงที่
test: wc
	@printf 'hello world\n'   > t1.txt
	@printf 'a b c\nd e\n'     > t2.txt
	@./wc t1.txt t2.txt > mine.raw || { echo "wc exited non-zero"; rm -f t1.txt t2.txt mine.raw; exit 1; }
	@awk '{$$1=$$1; print}' mine.raw > mine.txt
	@wc t1.txt t2.txt | awk '{$$1=$$1; print}' > real.txt
	@if diff mine.txt real.txt; then echo PASS; rc=0; else echo FAIL; rc=1; fi; \
	 rm -f t1.txt t2.txt mine.raw mine.txt real.txt; exit $$rc

สองกับดักในบรรทัด test เดิม: (1) cmd && echo PASS || echo FAIL ทำให้ recipe สำเร็จเสมอเพราะสถานะสุดท้ายมาจาก echo — ต้อง exit 1 เอง (2) ./wc ... | awk ... ใช้สถานะของ awk โปรแกรม wc จะ crash ก็ยังผ่าน — รัน wc ลงไฟล์แล้วเช็คสถานะก่อนส่งให้ awk

make เรียก recipe ผ่าน /bin/sh ซึ่งไม่รองรับ <(...) (process substitution ของ bash) ถ้าจำเป็นต้องใช้จริง ใส่ SHELL := /bin/bash ไว้ต้น Makefile

รัน

make
printf "one two three\nfour five\nsix\n" > sample.txt
./wc sample.txt
       3        6       28 sample.txt
./wc -l sample.txt
#        3 sample.txt

echo -e "a b\nc d e" | ./wc -w
#        5

หลายไฟล์:

./wc *.txt
       3        6       28 sample.txt
      10       42      301 notes.txt
      13       48      329 total

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

ส่วนบท
argc/argv, stdin, exit code24
อ่าน stdin เมื่อไม่มีไฟล์ (pipe ได้)24
getc() คืน int (แยก EOF)24
isspace จาก <ctype.h>36
struct Counts, struct Flags17
"rb" binary mode สำหรับนับไบต์23
fopen เช็ค NULL, perror22, 32
ทำงานต่อเมื่อไฟล์หนึ่งเปิดไม่ได้ (rc=1 แต่ไม่หยุด)32

ต่อยอด

  • -m — นับ character (ไม่ใช่ byte) โดยรู้ UTF-8: นับเฉพาะไบต์ที่ (b & 0xC0) != 0x80
  • -L — ความยาวบรรทัดที่ยาวที่สุด
  • จัดคอลัมน์ให้ชิดตาม wc จริง — ความกว้างขึ้นกับตัวเลขสูงสุด
  • getopt — parse flag ด้วยไลบรารีแทนเขียนเอง (บทที่ 24)
  • buffered read — fread ทีละ 64 KB แล้ววนใน buffer เร็วกว่า getc ทีละตัว

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

  • getc เก็บใน char — 0xFF กับ EOF แยกไม่ออก ใช้ int ch
  • นับบรรทัดจาก \n แต่บรรทัดสุดท้ายไม่มี \n — wc จริงก็นับแบบนี้ (จำนวน \n = จำนวนบรรทัดที่ “สมบูรณ์”)
  • ไม่รองรับ - เป็น stdin — เครื่องมือ Unix ควรรับ - แทน stdin
  • หยุดทั้งโปรแกรมเมื่อไฟล์แรกเปิดไม่ได้ — ควร continue ไปไฟล์ถัดไป ตั้ง rc=1
  • ไม่แสดง total เมื่อมีหลายไฟล์
  • เปิดไฟล์ text mode บน Windows — จำนวนไบต์เพี้ยน (\r\n แปลง) ใช้ "rb"
  • isspace(ch) เมื่อ ch เป็นค่าลบ (ไม่น่าเกิดเพราะเก็บใน int จาก getc แต่) — cast (unsigned char) ถ้าไม่มั่นใจ
  • getc คืน EOF แล้วถือว่าจบไฟล์เสมอ — EOF เกิดตอนอ่านพลาดก็ได้ เช็ค ferror(f) ทั้งไฟล์และ stdin แล้วตั้ง rc=1 ไม่งั้นรายงานตัวเลขไม่ครบพร้อม exit 0
  • make test ที่เขียน diff ... || echo FAIL — recipe คืน 0 เสมอ CI จับ fail ไม่ได้ ต้อง exit 1 เอง
  • prog | awk ... ใน make test — สถานะเป็นของ awk โปรแกรม crash ก็ยังผ่าน รันลงไฟล์แล้วเช็คสถานะก่อน
  • ไม่เช็ค fflush(stdout)/ferror(stdout) ก่อนจบ — เขียนผลลง pipe/redirect ที่เต็มแล้วล้มเหลว แต่ยัง exit 0

สรุป

  • อ่านทีละตัวอักษรด้วย getc() (คืน int), นับ: \n → บรรทัด, เข้า/ออก whitespace → คำ, ทุกตัว → ไบต์
  • ไม่มีไฟล์ → อ่าน stdin (pipe ได้); - = stdin ในรายการไฟล์
  • flag -lwc รวมกันได้ (-lw); ไม่ระบุ = แสดงทั้งหมด
  • หลายไฟล์ → แสดงต่อไฟล์ + บรรทัด total
  • ไฟล์เปิดไม่ได้ → error ไป stderr, rc=1, ทำไฟล์ถัดไปต่อ
  • getc คืน EOF ตอนอ่านพลาดได้ด้วย → เช็ค ferror() ทุก stream ตั้ง rc=1
  • ก่อนจบ เช็ค fflush(stdout)/ferror(stdout) — เขียนผลลัพธ์ล้มเหลวก็ต้องคืน error
  • "rb" เพื่อให้จำนวนไบต์ถูกต้อง (บน Windows long มัก 32 บิต และ stdin ยังเป็น text mode — จำกัดคำว่า “ทุก OS”)

บทถัดไป โปรเจกต์สร้าง hash map — string → int ด้วย separate chaining