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

问题描述 投票:-2回答:2

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

我不知道如何实现这个“-c”选项,我甚至不知道在谷歌或任何东西上输入什么。感谢任何可以帮助我的人

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

c linux command-line-arguments
2个回答
0
投票

如果将main()函数声明为

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

   return 0;
}

传递给程序的参数将作为字符串显示在argv参数中。 here给出了如何查询它们的示例。

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


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;
}
© www.soinside.com 2019 - 2024. All rights reserved.