0

optarg次の場合になぜ無効なパスを返すの--foo=~/.bashrcか疑問に思っています--foo ~/.bashrc

そして、両方のケースで機能するように、回避策は何でしょうか。

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

int main(int argc, char *argv[]) {
    int opt = 0;
    int long_index = 0;
    char *f; 
    static struct option longopt[] = { 
        {"foo", required_argument, 0,  'd' },
        {0,0,0,0}
    };  
    while ((opt = getopt_long(argc, argv,"d:", longopt, &long_index )) != -1) {
        switch (opt) {
            case 'd' : 
                printf("\n%s\n", optarg);
                f = realpath (optarg, NULL);
                if (f) printf("%s\n", f); 
                break;
            default: 
                exit(1);
        }   
    }   
    return 0;
}

出力:

$ ./a.out --foo=~/.bashrc
  ~/.bashrc

$ ./a.out --foo ~/.bashrc
  /home/user/.bashrc
4

1 に答える 1