gpt4 book ai didi

c - 解析命令行选项

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:24 25 4
gpt4 key购买 nike

<分区>

我写了一些代码,打印了命令行帮助:

int main(int argc, char **argv)

printf("$ ./porfolio6 --help \n"
"Usage: ./portfolio6 options [FILENAME]\n"

" -h --help Dsiplay this usage information.\n"
" -n --num Display my student number.\n"
" -c --chars Print number of characters in FILENAME.\n"
" -w --words Print number of words in FILENAME.\n"
" -l --lines Print number of lines in FILENAME.\n"
" -f --file FILENAME Read from file.\n");
}

我想知道如何使这些选项真正起作用。目前他们只是打印输出而不执行选项要求的操作。

@Apoorv@卡尔诺鲁姆我的代码更新版本是这样的,但我仍然遇到一些问题,无法让所有内容作为选项显示在终端上

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>


void print_usage() {
printf("Usage: ./portfolio6 options [FILENAME] \n");
}

int main(int arg, char *argc[]) {

int opt =0;
int help = -1, num = -1, chars = -1, words = -1, lines = -1, file = -1;

static struct option long_options[] = {

{"help", required_argument, 0, 'h' },
{"num", required_argument, 0, 'n' },
{"chars", required_argument, 0, 'c' },
{"words", required_argument, 0, 'w' },
{"lines", required_argument, 0, 'l' },
{"file", required_argument, 0, 'f' },
};

int long_index =0;
while((opt= getopt_long(argc, argv,"hncwl:f:",
long_options, &long_index )) != -1 {

switch (opt) {
case 'h' : /* -h or --h */
help = 1;
break;

case 'n' : /* -n or --n */
num = 1;
break;

case 'c' : /* -c or --c */
chars = 1;
break;

case 'w' : /* -w or --w */
words = 1;
break;

case 'l' : /* -l or --l */
lines = 1;
break;

case 'f' : /* -f or --f */
file = 1;
break;
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com