如何在C中的可执行文件上实现选项?

时间:2019-04-05 13:32:32

标签: c linux command-line-arguments

我正在研究套接字程序。我需要从文档中获取有关服务器地址的信息。我需要能够更改运行可执行文件时从哪些文档中获取这些信息。 例如,如果我的程序名为client.c,则需要能够在终端中键入:./client -c Name_Of_The_Document,然后程序将从文件Name_Of_The_Document中获取这些信息。

我不知道如何实现此“ -c”选项,我什至不知道在google上键入什么。感谢任何可以帮助我的人

我在工作中拥有所有要读取的代码,我只需要知道在运行可执行文件时如何在终端中更改要读取的文件。

2 个答案:

答案 0 :(得分:0)

您需要使用getopt函数。这是an example

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

int
main (int argc, char **argv)
{
  char *cvalue = NULL;
  int index;
  int c;

  opterr = 0;

  while ((c = getopt (argc, argv, "c:")) != -1)
    switch (c)
      {
      case 'c':
        cvalue = optarg;
        break;
      case '?':
        if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
        abort ();
      }

  printf ("cvalue = %s\n", cvalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}

答案 1 :(得分:0)

如果将main()函数声明为

div/@class
传递给程序的

参数将以字符串形式出现在argv参数中。 here给出了一个如何查询它们的示例。

然后您可以实现处理打开和读取文件的代码。