getopt() เป็นฟังก์ชันมาตรฐาน POSIX สำหรับแยกวิเคราะห์ Command Line Options แบบ Unix/Linux รองรับ Short Options (Single Character) เช่น -f file.txt -v -o output
Syntax
int getopt(int argc, char *const argv[], const char *optstring);
Optstring Format
"abc" → Options -a, -b, -c (ไม่มี Argument)
"ab:c:" → -a ไม่มี Arg, -b และ -c ต้องมี Argument
":ab:c:" → นำหน้าด้วย : เพื่อแยก : (Missing Arg) และ ? (Unknown Option)
Global Variables
| Variable | คำอธิบาย |
optarg | Pointer ไปยัง Argument ของ Option ปัจจุบัน (ถ้ามี) |
optind | Index ของ Argument ถัดไปที่จะ Process (สำหรับ Non-option Args) |
optopt | ตัวอักษร Option ที่ Error (Unknown หรือ Missing Arg) |
opterr | Set 0 เพื่อปิด Error Message Default |
ค่าคืน
- ตัวอักษร Option ที่พบ (เช่น
'f')
-1: ไม่มี Option เหลือแล้ว
'?': Unknown Option หรือ Missing Argument (ถ้าไม่มี : นำหน้า)
':': Missing Argument (ถ้ามี : นำหน้า optstring)
ตัวอย่างโค้ดครบถ้วน
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int option;
// ':' นำหน้า: แยก : (missing arg) และ ? (unknown option)
// 'i', 'l', 'r' = ไม่มี argument
// 'f:' = ต้องมี argument (filename)
// 'x' = ไม่มี argument
while ((option = getopt(argc, argv, ":if:lrx")) != -1) {
switch (option) {
case 'i':
case 'l':
case 'r':
printf("Given Option: %c\n", option);
break;
case 'f': // Option ที่ต้องการ Argument
printf("Given File: %s\n", optarg);
break;
case ':': // Missing Argument (เพราะมี : นำหน้า)
printf("Option -%c needs a value\n", optopt);
break;
case '?': // Unknown Option
printf("Unknown option: -%c\n", optopt);
break;
}
}
// Non-option Arguments (Operand)
for (; optind < argc; optind++) {
printf("Extra argument: %s\n", argv[optind]);
}
return 0;
}
ตัวอย่างการรัน
$ ./program -i -f test_file.c -l -r hello
Given Option: i
Given File: test_file.c
Given Option: l
Given Option: r
Extra argument: hello
กรณี Error Handling
$ ./program -f
Option -f needs a value
$ ./program -z
Unknown option: -z
ข้อจำกัดและทางเลือก
- getopt(): รองรับเฉพาะ Short Options (
-a, -b)
- getopt_long(): รองรับ Long Options (
--help, --version) - GNU Extension
- argp: GNU Advanced Argument Parser (ซับซ้อนกว่า แต่ powerful)
- Windows: ใช้
getopt ไม่ได้โดยตรง ต้อง Port หรือใช้ Library อื่น
getopt_long() ตัวอย่างสั้น
#include <getopt.h>
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'v'},
{"file", required_argument, 0, 'f'},
{0, 0, 0, 0}
};
int c;
while ((c = getopt_long(argc, argv, "hvf:", long_options, NULL)) != -1) {
// ... switch case เหมือนเดิม
}