就我们目前用的功能来说,用它来识别环境变量,并把它扩展出来,如,在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