C中使用getopt_long的文件路径无效
我想知道为什么C中使用getopt_long的文件路径无效,c,path,getopt-long,C,Path,Getopt Long,我想知道为什么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
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;
}
发生这种情况是因为“tilde扩展”是由shell执行的:它本身不是有效的路径。只有当tilde~位于字符串参数(看起来像路径)的开头时,才会将其扩展为主目录。例如:
$ echo ~
/home/sigi
$ echo ~/a
/home/sigi/a
$ echo ~root/a
/root/a
$ echo ~a
~a
$ echo a/~
a/~
如果您想在第一种情况下也提供此功能,而shell无法帮助您,或者更一般地说是shell使用的单词扩展,那么您可以在中找到所有需要的信息来自己完成此操作。这是shell扩展的问题。在启动程序之前,以~开头的参数将扩展到主目录。因为--foo=~/.bashrc是一个单独的参数,并且不是以~,所以这里不执行扩展。谢谢。因此,我猜shell无法扩展它,因为它认为
=~/.bashrc
是路径。您知道这是否是所有shell中的已知问题吗?它将--foo=~/.bashrc
视为一个参数,而不是以~开头。但是,必须有一种方法教bash在=
之后展开~
,因为它对dd
命令进行了正确的展开。例如,dd如果=~/xxx
展开。这是bash社区的问题。不知道。谢谢
$ echo ~
/home/sigi
$ echo ~/a
/home/sigi/a
$ echo ~root/a
/root/a
$ echo ~a
~a
$ echo a/~
a/~