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 code | 24 |
| อ่าน stdin เมื่อไม่มีไฟล์ (pipe ได้) | 24 |
getc() คืน int (แยก EOF) | 24 |
isspace จาก <ctype.h> | 36 |
struct Counts, struct Flags | 17 |
"rb" binary mode สำหรับนับไบต์ | 23 |
fopen เช็ค NULL, perror | 22, 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 0make 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"เพื่อให้จำนวนไบต์ถูกต้อง (บน Windowslongมัก 32 บิต และ stdin ยังเป็น text mode — จำกัดคำว่า “ทุก OS”)
บทถัดไป โปรเจกต์สร้าง hash map — string → int ด้วย separate chaining