在看alsa-lib代码时,跟踪它对配置文件的解析时遇到了这个函数,虽然对调用它的函数的功能了解但是对wordexp()本身不是很清楚,于是google一下,才发现,原来这个玩意儿挺不错的。
就我们目前用的功能来说,用它来识别环境变量,并把它扩展出来,如,在shell下使用 echo $HOME 可以很容易的打印出来当前的home路径,在源码如何获取这个home的路经呢,可能会用getenv()这个东西。这时还不足以体现wordexp()的强大,再如果想获取目录下的*.c文件名,给怎么获取呢,此时就可以考虑使用wordexp()。当然也可以不使用它,直接获取目录下文件们,然后再逐个的判断。但是用wordexp()会更简单。
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <wordexp.h>
-
-
int main(int argc, char **argv)
-
{
-
wordexp_t p;
-
char **w;
-
int i;
-
-
wordexp("ls -al *.c", &p, 0);
-
w = p.we_wordv;
-
for (i = 0; i < p.we_wordc; i++)
-
printf("%s\n", w[i]);
-
wordfree(&p);
-
exit(EXIT_SUCCESS);
-
}
-
[blue@blue testwordexp]$ ls
-
main.c
-
[blue@blue testwordexp]$ gcc main.c -o test
-
[blue@blue testwordexp]$ ./test ls -al *.c
-
ls
-
-al
-
main.c
-
[blue@blue testwordexp]$
最开始我在想不就是复制个文件名吗,搞这么复杂干吗?如果我直接输入一个绝对路径的文件名肯定不会用上这个接口,问题就是,肯定不会所有调用它的人都会完完整整的输入绝对路径,因为还有相对路径和环境变量这些东西,用他们也可以构造出一个文件的路径,这时就要用其他方法来解析了。于是霍然开朗了。
你不在地铁里吃东西,并不能以此就来幻想别人不在那里吃热干面。
alsa-lib/src/userfile.c
-
34
-
35 #ifdef HAVE_WORDEXP_H
-
36 #include <wordexp.h>
-
37 #include <assert.h>
-
38 int snd_user_file(const char *file, char **result)
-
39 {
-
40 wordexp_t we;
-
41 int err;
-
42
-
43 assert(file && result);
-
44 err = wordexp(file, &we, WRDE_NOCMD);
-
45 switch (err) {
-
46 case WRDE_NOSPACE:
-
47 return -ENOMEM;
-
48 case 0:
-
49 if (we.we_wordc == 1)
-
50 break;
-
51 /* fall thru */
-
52 default:
-
53 wordfree(&we);
-
54 return -EINVAL;
-
55 }
-
56 *result = strdup(we.we_wordv[0]);
-
57 if (*result == NULL)
-
58 return -ENOMEM;
-
59 wordfree(&we);
-
60 return 0;
-
61 }
-
62
-
63 #else /* !HAVE_WORDEXP_H */
-
64 /* just copy the string - would be nicer to expand by ourselves, though... */
-
65 int snd_user_file(const char *file, char **result)
-
66 {
-
67 *result = strdup(file);
-
68 if (! *result)
-
69 return -ENOMEM;
-
70 return 0;
-
71 }
-
72 #endif /* HAVE_WORDEXP_H */
参考连接:
http://blog.chinaunix.net/uid-24774106-id-3237465.html
阅读(3242) | 评论(0) | 转发(0) |