【问题标题】:How to implement options on an executable in c?如何在c中的可执行文件上实现选项?
【发布时间】:2019-08-27 10:16:57
【问题描述】:

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

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

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

【问题讨论】:

标签: c linux command-line-arguments


【解决方案1】:

如果您将 main() 函数声明为

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

   return 0;
}

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

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

【讨论】:

    【解决方案2】:

    您需要使用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;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 2012-06-12
      • 2010-09-12
      • 2023-03-25
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多