C中使用getopt_long的文件路径无效
-
26-12-2019 - |
题
我想知道为什么 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
解决方案
它的发生是因为"波浪号扩展"是由shell执行的:它本身不是一个有效的路径。波浪号~仅在字符串参数开头的情况下作为主目录展开,这看起来像一个路径。例如:
$ echo ~
/home/sigi
$ echo ~/a
/home/sigi/a
$ echo ~root/a
/root/a
$ echo ~a
~a
$ echo a/~
a/~
如果您也想在shell无法帮助您的第一种情况下提供此功能,或者更一般地说是shell使用的单词扩展,您可以在 这个参考.
不隶属于 StackOverflow