我正在尝试完成我的大学作业,该作业需要在 Unix 中使用 C 进行编程。我必须采用命令行参数并打开一个名称作为参数传递的文件。我一直在寻求帮助,但找不到任何资源来帮助我理解如何将参数解析为字符串并打开所需的文件。我正在寻找为我指明正确方向的示例或链接。
我包含了一小段代码,我在其中尝试使用 getopt() 解析选项。我做错了什么?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(int argc[], char *argv[])
{
int option;
while(option = getopt(argc, argv, "hi:o:") != -1)
{
switch (option){
case 'h':
printf("Usage : -i [input file name]\n-o [output file name]");
break;
case 'i':
printf("\n Input file is: %s",argv[1]);
break;
case 'o':
printf("\n Output file is: %s",argv[2]);
break;
}
}
return 0;
}
我不断收到“无法识别的命令行选项错误”。此外,当我尝试包含一个文本文件时,我认为错误表明该选项被解析为一个 int,但参数是一个字符串。
P.S:我真的不想在这里得到任何直接的答案。我希望社区帮助我以最好的方式学习。
最佳答案
如评论中所述,您应该使用 optarg
。这是一个非常全面的示例:
/*
example of command line parsing via getopt
usage: getopt [-dmp] -f fname [-s sname] name [name ...]
Paul Krzyzanowski
*/
#include <stdio.h>
#include <stdlib.h>
int debug = 0;
int
main(int argc, char **argv)
{
extern char *optarg;
extern int optind;
int c, err = 0;
int mflag=0, pflag=0, fflag=0;
char *sname = "default_sname", *fname;
static char usage[] = "usage: %s [-dmp] -f fname [-s sname] name [name ...]\n";
while ((c = getopt(argc, argv, "df:mps:")) != -1)
switch (c) {
case 'd':
debug = 1;
break;
case 'm':
mflag = 1;
break;
case 'p':
pflag = 1;
break;
case 'f':
fflag = 1;
fname = optarg;
break;
case 's':
sname = optarg;
break;
case '?':
err = 1;
break;
}
if (fflag == 0) { /* -f was mandatory */
fprintf(stderr, "%s: missing -f option\n", argv[0]);
fprintf(stderr, usage, argv[0]);
exit(1);
} else if ((optind+1) > argc) {
/* need at least one argument (change +1 to +2 for two, etc. as needeed) */
printf("optind = %d, argc=%d\n", optind, argc);
fprintf(stderr, "%s: missing name\n", argv[0]);
fprintf(stderr, usage, argv[0]);
exit(1);
} else if (err) {
fprintf(stderr, usage, argv[0]);
exit(1);
}
/* see what we have */
printf("debug = %d\n", debug);
printf("pflag = %d\n", pflag);
printf("mflag = %d\n", mflag);
printf("fname = \"%s\"\n", fname);
printf("sname = \"%s\"\n", sname);
if (optind < argc) /* these are the arguments after the command-line options */
for (; optind < argc; optind++)
printf("argument: \"%s\"\n", argv[optind]);
else {
printf("no arguments left to process\n");
}
exit(0);
}
此示例和更多信息可在 here 中找到.
关于C 程序帮助使用 getopt 和命令行参数在 Unix/Linux 中打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54451019/