system-programming:getopt
تفاوتها
تفاوت دو نسخهٔ متفاوت از صفحه را مشاهده میکنید.
| system-programming:getopt [2024/04/19 18:01] – ایجاد شد pejman | system-programming:getopt [2024/06/18 01:21] (فعلی) – حذف شد pejman | ||
|---|---|---|---|
| خط 1: | خط 1: | ||
| - | ====== تابع ()getopt - تفسیر پارامترهای خط فرمان ====== | ||
| - | |||
| - | |||
| - | از این تابع برای تشخیص سوئیچ هایی که در خط فرمان نوشته شده اند استفاده میشود. | ||
| - | <code C> | ||
| - | #include < | ||
| - | |||
| - | int getopt(int argc, char * const argv[], const char *optstring); | ||
| - | </ | ||
| - | |||
| - | man 3 getopt | ||
| - | | ||
| - | # _XOPEN_SOURCE | ||
| - | man 7 feature_test_macros | ||
| - | |||
| - | <code C> | ||
| - | /* new-sum.c */ | ||
| - | #define _XOPEN_SOURCE 500 | ||
| - | #include < | ||
| - | #include < | ||
| - | #include < | ||
| - | void printhelp(char progname[]); | ||
| - | |||
| - | int main(int argc, char *argv[]) | ||
| - | { | ||
| - | int i, opt, sum; | ||
| - | |||
| - | /* Simple sanity check */ | ||
| - | if (argc == 1) | ||
| - | { | ||
| - | printhelp(argv[0]); | ||
| - | return 1; | ||
| - | } | ||
| - | |||
| - | /* Parse command-line options */ | ||
| - | while ((opt = getopt(argc, | ||
| - | { | ||
| - | switch (opt) | ||
| - | { | ||
| - | case ' | ||
| - | sum = 0; | ||
| - | for (i=2; i<argc; i++) | ||
| - | sum = sum + atoi(argv[i]); | ||
| - | break; | ||
| - | case ' | ||
| - | sum = 1; | ||
| - | for (i=2; i<argc; i++) | ||
| - | sum = sum * atoi(argv[i]); | ||
| - | break; | ||
| - | case ' | ||
| - | printhelp(argv[0]); | ||
| - | return 0; | ||
| - | default: /* in case of invalid options*/ | ||
| - | printhelp(argv[0]); | ||
| - | return 1; | ||
| - | } | ||
| - | } | ||
| - | printf(" | ||
| - | return 0; | ||
| - | } | ||
| - | |||
| - | void printhelp(char progname[]) | ||
| - | { | ||
| - | printf(" | ||
| - | printf(" | ||
| - | "-m multiplies all the integers\n" | ||
| - | "This program takes any number of integer " | ||
| - | " | ||
| - | "For example: %s -m 5 5 5\n", progname); | ||
| - | } | ||
| - | |||
| - | </ | ||
| - | |||
| - | $ make new-sum | ||
| - | cc | ||
| - | |||
| - | $ ./new-sum | ||
| - | ./new-sum [-s] [-m] integer ... | ||
| - | -s sums all the integers | ||
| - | -m multiplies all the integers | ||
| - | This program takes any number of integer values and either add or multiply them. | ||
| - | For example: ./new-sum -m 5 5 5 | ||
| - | |||
| - | $ ./new-sum -s 5 5 5 | ||
| - | Total: 15 | ||
| - | |||
| - | $ ./new-sum -m 5 5 5 | ||
| - | Total: 125 | ||
| - | |||
system-programming/getopt.1713537073.txt.gz · آخرین ویرایش: 2024/04/19 18:01 توسط pejman
