如何从optarg中获取值

Mat*_*usz 7 c getopt

嗨,我正在写一个简单的客户端 - 服务器程序.在这个程序中,我必须使用getopt()这样获取端口号和IP地址:

server -i 127.0.0.1 -p 10001

我不知道如何从optarg中获取值,以便稍后在程序中使用.

mcd*_*ave 14

你使用while循环遍历所有参数并像这样处理它们......

#include <unistd.h>

int main(int argc, char *argv[])
{
    int option = -1;
    char *addr, *port;

    while ((option = getopt (argc, argv, "i:p:")) != -1)
    {
         switch (option)
         {
         case 'i':
             addr = strdup(optarg);
             break;
         case 'p':
             port = strdup(optarg);
             break;
         default:
              /* unrecognised option ... add your error condition */
              break;
         }
    }

    /* rest of program */

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果在退出之前没有释放它们,`strdup`会导致内存泄漏.所以在你的例子中,你需要释放`addr`和`port`. (2认同)

Kor*_*icz 5

像这样怎么样:

char buf[BUFSIZE+1];
snprintf(buf,BUFSIZE,"%s",optarg);
Run Code Online (Sandbox Code Playgroud)

或者在更完整的示例中:

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

#define BUFSIZE 16

int main( int argc, char **argv )
{
    char c;
    char port[BUFSIZE+1];
    char addr[BUFSIZE+1];

    while(( c = getopt( argc, argv, "i:p:" )) != -1 )
        switch ( c )
        {
            case 'i':
                snprintf( addr, BUFSIZE, "%s", optarg );
                break;
            case 'p':
                snprintf( port, BUFSIZE, "%s", optarg );
                break;
            case '?':
                fprintf( stderr, "Unrecognized option!\n" );
                break;
        }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Getopt的文档。

  • 使用strdup的答案是这个问题的更好的解决方案。它避免为未知长度的字符串创建固定大小的缓冲区 (2认同)