问题描述
嗨,我正在编写一个简单的客户服务器程序.在此程序中,我必须使用getopt()以获取这样的端口号和IP地址:
服务器-i 127.0.0.1 -p 10001
我不知道如何从Optarg获得值,以后在程序中使用.
推荐答案
这样怎么样:
char buf[BUFSIZE+1]; snprintf(buf,BUFSIZE,"%s",optarg);
或更完整的示例:
#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; }
有关更多信息,请参见 getopt 的文档.
其他推荐答案
您使用一个way循环在所有参数中移动并像这样处理它们...
#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; }
其他推荐答案
它是GetOpt文档的众多缺陷之一:它不清楚地说必须复制Optarg以供以后使用(例如,使用strdup()),因为它可能会被以后的选项覆盖或仅由由Getopt释放.