字符串C上的getopt()

字符串C上的getopt(),c,linux,getopt,C,Linux,Getopt,如何使用C在字符串上实现类似getopt()的函数 我现在正在申请这个 #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <strings.h> #include <fcntl.h> int main(int argc, char **argv){ int ch,fd; char *ip; char *port;

如何使用C在字符串上实现类似getopt()的函数

我现在正在申请这个

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <strings.h>
#include <fcntl.h>


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

     int ch,fd;
     char *ip;
     char *port;
     char *user;
     char message[100]; 
     message = "_connect -i 127.0.0.1 -p 1234 -u hello1";

     while ((ch = getopt(argc, argv, "i:p:u:")) != -1) {
             switch (ch) {
             case 'i':
                     if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
                             printf("my ip is: %s\n", optarg);

                             //ip = optarg;
                     }
                     break;

            case 'p':
                    if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
                             printf("my port number is: %s\n", optarg);
                             //port = optarg;

                     }
                     break;

            case 'u':
                    if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
                             printf("my name is: %s\n", optarg);
                             //user = optarg;

                     }
                     break;
             default:break;
             }
     }
     argc -= optind;
     argv += optind;
     return 0;
  }
#包括
#包括
#包括
#包括
#包括
int main(int argc,字符**argv){
int-ch,fd;
字符*ip;
字符*端口;
字符*用户;
字符消息[100];
message=“_connect-i 127.0.0.1-p 1234-u hello1”;
while((ch=getopt(argc,argv,“i:p:u:”)!=-1){
开关(ch){
案例“i”:
如果((fd=optarg,Orduonly,0))<0){
printf(“我的ip是:%s\n”,optarg);
//ip=optarg;
}
打破
案例“p”:
如果((fd=optarg,Orduonly,0))<0){
printf(“我的端口号是:%s\n”,optarg);
//端口=optarg;
}
打破
案例“u”:
如果((fd=optarg,Orduonly,0))<0){
printf(“我的名字是:%s\n”,optarg);
//用户=optarg;
}
打破
默认:中断;
}
}
argc-=optind;
argv+=optind;
返回0;
}

我需要使消息完全作为参数和getopt函数来接收单独的值。请首先使用
strtok
(或
strtok\u r
)将C字符串转换为字符串数组。然后将其传递到
getopt
getopt
只使用
argc
argv
,因为这是您要传递的

如果你需要关注引用(考虑是否

hello "foo bar" baz

有三个或两个参数),那么您可能需要查看,或者如果您使用的是
glib

如果多次调用getopt,请不要忘记重置optind。