C ไฟล์ text เทียบ binary



text mode vs binary mode

FILE *ft = fopen("data.txt", "r");    // text mode
FILE *fb = fopen("data.bin", "rb");   // binary mode

ความต่าง:

  • บน Windows text mode แปลง \r\n (บนดิสก์) ↔ \n (ในโปรแกรม) อัตโนมัติ binary mode ไม่แปลง — อ่านไบต์ตรง ๆ
  • บน Linux/macOS ไม่มีความต่าง (\n อย่างเดียวอยู่แล้ว)

กฎ: ไฟล์ข้อความใช้ "r"/"w", ไฟล์อื่น (รูป, struct, ข้อมูล binary) ใช้ "rb"/"wb" เสมอ — เขียนโค้ดให้ portable

fwrite / fread — อ่านเขียนเป็นบล็อก

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *f);
size_t fread(void *ptr, size_t size, size_t count, FILE *f);
  • size — ขนาดของแต่ละสมาชิก (ไบต์)
  • count — จำนวนสมาชิก
  • คืนจำนวนสมาชิกที่อ่าน/เขียนสำเร็จจริง (< count = จบไฟล์หรือ error)
#include <stdio.h>

int main(void)
{
    int nums[5] = {10, 20, 30, 40, 50};

    // เขียน
    FILE *f = fopen("nums.bin", "wb");
    if (!f) { perror("nums.bin"); return 1; }
    size_t written = fwrite(nums, sizeof(int), 5, f);
    if (written != 5) { fprintf(stderr, "เขียนไม่ครบ\n"); }
    fclose(f);

    // อ่าน
    int loaded[5];
    f = fopen("nums.bin", "rb");
    if (!f) { perror("nums.bin"); return 1; }
    size_t got = fread(loaded, sizeof(int), 5, f);
    fclose(f);

    for (size_t i = 0; i < got; i++) printf("%d ", loaded[i]);   // 10 20 30 40 50
    printf("\n");
    return 0;
}

ไฟล์ nums.bin มี 20 ไบต์ (5 × 4) — ไม่ใช่ข้อความ เปิดด้วย text editor จะเห็นขยะ

fseek / ftell / rewind — เลื่อนตำแหน่ง

fseek(f, 0, SEEK_END);     // ไปท้ายไฟล์
long size = ftell(f);      // ตำแหน่งปัจจุบัน = ขนาดไฟล์ (ไบต์)

fseek(f, 0, SEEK_SET);     // ไปต้นไฟล์ (= rewind(f))
fseek(f, 100, SEEK_SET);   // ไปไบต์ที่ 100 จากต้น
fseek(f, -4, SEEK_CUR);    // ถอยหลัง 4 ไบต์จากตำแหน่งปัจจุบัน
fseek(f, -8, SEEK_END);    // ไปไบต์ที่ 8 นับจากท้าย

SEEK_SET (ต้น), SEEK_CUR (ปัจจุบัน), SEEK_END (ท้าย)

อ่าน record ที่ i จากไฟล์ที่เก็บ struct ขนาดเท่ากัน:

typedef struct { int id; char name[32]; double balance; } Account;

Account read_account(FILE *f, long index)
{
    Account acc;
    fseek(f, index * sizeof(Account), SEEK_SET);
    fread(&acc, sizeof(Account), 1, f);
    return acc;
}

ftell คืน long — ไฟล์ > 2 GB บนบางระบบต้องใช้ fseeko/ftello (POSIX) กับ off_t

while (!feof(f)) — ทำไมผิด

// ❌ บั๊กคลาสสิก
while (!feof(f)) {
    fgets(line, sizeof(line), f);
    printf("%s", line);           // บรรทัดสุดท้ายพิมพ์ซ้ำ!
}

feof เป็นจริง หลังจาก พยายามอ่านแล้วเจอ EOF ไม่ใช่ก่อน ลำดับที่เกิด:

  1. อ่านบรรทัดสุดท้ายสำเร็จ — feof ยัง เท็จ
  2. loop วนอีกรอบ, fgets เจอ EOF คืน NULL, line ไม่ถูกอัปเดต (ยังมีข้อมูลเก่า)
  3. พิมพ์ line เดิมซ้ำ
  4. ตอนนี้ feof จริง loop จบ

แก้: เช็คค่าคืนของฟังก์ชันอ่าน

// ✅
while (fgets(line, sizeof(line), f) != NULL) {
    printf("%s", line);
}

while (fread(&record, sizeof(record), 1, f) == 1) {
    process(&record);
}

feof / ferror ใช้ หลัง loop เพื่อดูว่าจบเพราะอะไร

เขียน struct ลงไฟล์ — ไม่ portable

Account acc = {1, "อร", 5000.0};
fwrite(&acc, sizeof(acc), 1, f);   // เขียนไบต์ดิบของ struct

ปัญหา:

  • padding — คอมไพเลอร์/สถาปัตยกรรมต่างกัน layout ต่าง (บทที่ 18)
  • endianness — x86 เก็บ int little-endian, บางเครื่อง big-endian
  • ขนาดชนิด — long 4 หรือ 8 ไบต์ตามระบบ

ใช้ได้ถ้าไฟล์อ่านบนเครื่อง/คอมไพเลอร์เดียวกันเสมอ (เช่น cache ชั่วคราว) แต่ สำหรับไฟล์ที่ต้องแลกเปลี่ยน ให้กำหนด format เอง: เขียนทีละ field ด้วยขนาดชัดเจน (uint32_t), ระบุ endianness, หรือใช้ text/JSON

hex dump ไฟล์ binary

FILE *f = fopen("nums.bin", "rb");
unsigned char byte;
int col = 0;
while (fread(&byte, 1, 1, f) == 1) {
    printf("%02x ", byte);
    if (++col % 16 == 0) printf("\n");
}
fclose(f);
0a 00 00 00 14 00 00 00 1e 00 00 00 28 00 00 00
32 00 00 00

(10, 20, 30, 40, 50 แบบ little-endian int)

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

  • while (!feof(f)) — พิมพ์/ประมวลผลบรรทัดสุดท้ายซ้ำ เช็คค่าคืนของ fgets/fread แทน
  • เปิดไฟล์ binary ด้วย "r" บน Windows — \r\n ถูกแปลง, 0x1A ถือเป็น EOF ใช้ "rb"
  • fread(buf, sizeof(buf), 1, f) เมื่อ buf เป็น pointer — sizeof = 8 ไม่ใช่ขนาด buffer
  • สลับ size กับ count ใน fread/fwrite — ผลรวมเท่ากันแต่ค่าคืนต่างความหมาย
  • fwrite struct แล้วอ่านบนเครื่องอื่น — padding/endianness พัง กำหนด format เอง
  • ftell กับไฟล์ที่เปิด text mode บน Windows — ค่าอาจไม่ใช่ byte offset จริง
  • fseek เกินขนาดไฟล์แล้ว fwrite — สร้าง “hole” (sparse file) ไบต์ตรงกลางเป็น 0

สรุป

  • text mode แปลง \r\n↔\n บน Windows — ใช้ "rb"/"wb" สำหรับข้อมูลที่ไม่ใช่ข้อความ
  • fread(ptr, size, count, f) / fwrite(...) — คืนจำนวนสมาชิกที่สำเร็จ, เช็คเทียบ count
  • fseek(f, offset, SEEK_SET|CUR|END) + ftell(f) เลื่อน/หาตำแหน่ง; อ่าน record ที่ i = fseek(i * sizeof(rec))
  • อย่าใช้ while (!feof(f)) — เช็คค่าคืนของฟังก์ชันอ่าน, feof/ferror ใช้หลัง loop
  • fwrite struct ลงไฟล์ = ไม่ portable (padding, endianness) — กำหนด format เอง

บทถัดไปว่าด้วย argc/argv, stdin/stdout/stderr และ exit code — ทำโปรแกรม CLI ที่ทำงานกับ shell ได้ถูกต้อง