C printf/scanf ให้ครบและปลอดภัย



format specifier ครบชุด

%[flags][width][.precision][length]specifier

specifier

ชนิดตัวอย่าง
%d %iint (ฐาน 10)-42
%uunsigned int42
%oฐาน 852
%x %Xฐาน 16 (เล็ก/ใหญ่)2a / 2A
%f %Fdouble ทศนิยม3.140000
%e %Eเลขยกกำลัง3.14e+00
%g %Gสั้นที่สุดระหว่าง %f/%e3.14
%ccharA
%sสตริง (char *)hello
%ppointer0x7ffe...
%%เครื่องหมาย %%
%nเขียนจำนวน char ที่พิมพ์ไปแล้ว(อันตราย — หลายระบบปิด)

length modifier (สำคัญมาก — ผิดแล้ว UB)

ใช้กับ
%hdshort
%ldlong
%lldlong long
%zusize_t
%tdptrdiff_t
%lfdouble ใน scanf (printf ใช้ %f ก็ได้)
%jdintmax_t

จาก <inttypes.h> สำหรับ <stdint.h> types:

#include <inttypes.h>
uint64_t big = 1234567890123ULL;
printf("%" PRIu64 "\n", big);        // PRIu64 ขยายเป็น "lu" หรือ "llu" ตามระบบ
int32_t n = -5;
printf("%" PRId32 "\n", n);

width และ precision

printf("%5d\n",    42);       // "   42"     กว้าง 5 ชิดขวา
printf("%-5d|\n",  42);       // "42   |"    ชิดซ้าย
printf("%05d\n",   42);       // "00042"     เติม 0
printf("%+d\n",    42);       // "+42"       แสดงเครื่องหมายเสมอ
printf("%.3f\n",   3.14159);  // "3.142"     ทศนิยม 3 ตำแหน่ง
printf("%10.2f\n", 3.14159);  // "      3.14" กว้าง 10, ทศนิยม 2
printf("%.5s\n",   "hello world");  // "hello"  จำกัดสตริง 5 ตัวแรก
printf("%*d\n",    6, 42);     // "    42"    width จาก argument (6)
printf("%.*f\n",   2, 3.14159);  // "3.14"   precision จาก argument

snprintf — สร้างสตริงอย่างปลอดภัย

char buf[32];
int written = snprintf(buf, sizeof(buf), "user_%d_%s", 42, "backup");
// buf = "user_42_backup", written = 14

snprintf คืน “จำนวน char ที่ *ควรจะ* เขียน” (ไม่นับ '\0') ไม่ใช่ที่เขียนจริง — เช็ค truncation:

int need = snprintf(buf, sizeof(buf), "%s/%s/%s", a, b, c);
if (need < 0) {
    // encoding error
} else if ((size_t)need >= sizeof(buf)) {
    // ถูกตัด — buf มี need+1 ไบต์ไม่พอ
    fprintf(stderr, "path ยาวเกิน buffer\n");
}

snprintf ปิด '\0' ให้เสมอ (ถ้า size > 0) แม้ตัดข้อความ — ต่างจาก strncpy

ต่อสตริงอย่างปลอดภัย — ทำครั้งเดียวจบดีที่สุด:

char path[256];
int n = snprintf(path, sizeof(path), "%s/%s", dir, file);
if (n < 0 || (size_t)n >= sizeof(path)) {
    fprintf(stderr, "path ยาวเกิน buffer\n");
    return -1;
}

ถ้าจำเป็นต้องต่อทีละท่อน ต้องตรวจค่าคืนก่อนเลื่อน offset ทุกครั้ง — ห้ามเอาค่าคืนที่ยังไม่ตรวจไปบวกเป็น offset (ถ้า dir ยาว 300 แต่ path มี 256 len จะเป็น 300 แล้ว path + len เลยขอบ และ sizeof(path) - len วนเป็นค่ามหาศาล):

char path[256];
size_t len = 0;
int n;

n = snprintf(path + len, sizeof(path) - len, "%s", dir);
if (n < 0 || (size_t)n >= sizeof(path) - len) { /* ถูกตัด — จัดการ error */ return -1; }
len += (size_t)n;

n = snprintf(path + len, sizeof(path) - len, "/%s", file);
if (n < 0 || (size_t)n >= sizeof(path) - len) { /* ถูกตัด — จัดการ error */ return -1; }
len += (size_t)n;

อย่าใช้ sprintf (ไม่มีขนาด → buffer overflow) — ใช้ snprintf เสมอ

sscanf — แยกค่าจากสตริง

char line[] = "อร 25 3.75";
char name[50];
int age;
double gpa;

int n = sscanf(line, "%49s %d %lf", name, &age, &gpa);
if (n == 3) {
    printf("%s / %d / %.2f\n", name, age, gpa);
} else {
    printf("แยกได้แค่ %d field\n", n);
}
  • คืนจำนวน field ที่แปลงสำเร็จ (EOF ถ้าจบก่อนเจอ field แรก)
  • %d ใน scanf ต้อง &age, %s ไม่ต้อง & (อาร์เรย์ decay)
  • double ใช้ %lf ใน scanf (%f = float)
  • %s หยุดที่ whitespace, %[^\n] อ่านจนจบบรรทัด, %[0-9] อ่านเฉพาะตัวเลข

scanf(“%s”) — ช่องโหว่ buffer overflow

char name[10];
scanf("%s", name);            // ❌ ผู้ใช้พิมพ์ 50 ตัว → เขียนทะลุ name

scanf("%9s", name);           // ✅ จำกัด 9 ตัว + '\0' = 10

%s ใน scanf/sscanf ต้องมี width เสมอ (%9s สำหรับ buffer 10) ไม่งั้นเหมือน gets ที่ถูกลบไปแล้ว

ทางที่ปลอดภัยและควบคุมได้กว่า: fgets + sscanf

char line[256];
if (fgets(line, sizeof(line), stdin)) {
    line[strcspn(line, "\n")] = '\0';
    if (sscanf(line, "%d", &value) == 1) {
        // ...
    }
}

แปลงตัวเลขที่ตรวจ error ได้

sscanf/atoi บอก error ไม่ละเอียด ใช้ strtol/strtod:

#include <stdlib.h>
#include <errno.h>
#include <limits.h>   // INT_MIN, INT_MAX

int parse_int(const char *s, int *out)
{
    errno = 0;
    char *end;
    long v = strtol(s, &end, 10);

    if (end == s)            return -1;   // ไม่มีตัวเลขเลย
    if (*end != '\0')        return -2;   // มีอักขระเกิน ("42abc")
    if (errno == ERANGE)     return -3;   // เกินช่วง long
    if (v < INT_MIN || v > INT_MAX) return -4;

    *out = (int)v;
    return 0;
}

variadic function — printf ทำงานยังไง

#include <stdarg.h>

void log_msg(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);      // ส่ง va_list ต่อให้ vprintf family
    va_end(args);
    fprintf(stderr, "\n");
}

log_msg("error code %d at %s", 42, "startup");

va_start/va_arg/va_end เข้าถึง argument ที่ไม่ระบุชนิด — vprintf, vsnprintf รับ va_list ต่อ

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

  • specifier ไม่ตรง length — %d กับ long, %ld กับ int, %d กับ size_t — UB ใช้ %ld %zu ให้ตรง
  • scanf("%s", buf) ไม่มี width — buffer overflow เสมอใส่ %9s
  • snprintf return value คิดว่าคือจำนวนที่เขียนจริง — คือจำนวนที่ *ควร* เขียน เช็ค >= size = ถูกตัด
  • len += snprintf(buf + len, size - len, ...) โดยไม่ตรวจก่อน — พอถูกตัด len จะเกิน size แล้ว buf + len เลยขอบ, size - len วนเป็นค่ามหาศาล ตรวจค่าคืนก่อนบวกทุกครั้ง
  • sprintf ยังใช้อยู่ — ไม่มีขนาด, overflow ใช้ snprintf
  • double ใน scanf ใช้ %f — ต้อง %lf (ใน printf %f ได้)
  • จำนวน argument ไม่ตรงกับ % — printf("%d %d", x) อ่าน argument ตัวสองจากขยะ
  • %n — ช่องโหว่ (format string attack) หลายระบบปิด อย่าใช้
  • format string จาก user — printf(user_input) = format string vulnerability ใช้ printf("%s", user_input)

สรุป

  • %[flags][width][.precision][length]spec — จับ length ให้ตรงชนิด (%ld long, %zu size_t, %lf double ใน scanf)
  • <inttypes.h> มี PRIu64 ฯลฯ สำหรับ <stdint.h> types
  • snprintf เสมอ (ไม่ sprintf) — คืนจำนวนที่ *ควร* เขียน, >= size = ถูกตัด, ปิด '\0' เสมอ
  • sscanf แยกค่า — คืนจำนวน field, %d ต้อง &, %s ต้องมี width
  • scanf("%s") ต้องมี width (%9s) — ไม่งั้นคือ buffer overflow; ดีกว่าคือ fgets + sscanf
  • แปลงตัวเลขตรวจ error ได้ด้วย strtol/strtod + errno
  • อย่าใช้ user input เป็น format string

บทถัดไปว่าด้วยทัวร์ standard library — <stdlib.h>, <ctype.h>, <math.h>, <time.h>, <limits.h>