Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1071241
  • 博文数量: 132
  • 博客积分: 612
  • 博客等级: 中士
  • 技术积分: 1389
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-14 16:06
文章分类

全部博文(132)

文章存档

2015年(2)

2014年(55)

2013年(53)

2012年(2)

2011年(20)

分类: LINUX

2013-03-30 10:19:26

在看alsa-lib代码时,跟踪它对配置文件的解析时遇到了这个函数,虽然对调用它的函数的功能了解但是对wordexp()本身不是很清楚,于是google一下,才发现,原来这个玩意儿挺不错的。
就我们目前用的功能来说,用它来识别环境变量,并把它扩展出来,如,在shell下使用 echo $HOME 可以很容易的打印出来当前的home路径,在源码如何获取这个home的路经呢,可能会用getenv()这个东西。这时还不足以体现wordexp()的强大,再如果想获取目录下的*.c文件名,给怎么获取呢,此时就可以考虑使用wordexp()。当然也可以不使用它,直接获取目录下文件们,然后再逐个的判断。但是用wordexp()会更简单。


点击(此处)折叠或打开

  1. #include <stdio.h>
  2.        #include <stdlib.h>
  3.        #include <wordexp.h>

  4.        int main(int argc, char **argv)
  5.        {
  6.            wordexp_t p;
  7.            char **w;
  8.            int i;

  9.            wordexp("ls -al *.c", &p, 0);
  10.            w = p.we_wordv;
  11.            for (i = 0; i < p.we_wordc; i++)
  12.                printf("%s\n", w[i]);
  13.            wordfree(&p);
  14.            exit(EXIT_SUCCESS);
  15.        }


点击(此处)折叠或打开

  1. [blue@blue testwordexp]$ ls
  2. main.c
  3. [blue@blue testwordexp]$ gcc main.c -o test
  4. [blue@blue testwordexp]$ ./test ls -al *.c
  5. ls
  6. -al
  7. main.c
  8. [blue@blue testwordexp]$
最开始我在想不就是复制个文件名吗,搞这么复杂干吗?如果我直接输入一个绝对路径的文件名肯定不会用上这个接口,问题就是,肯定不会所有调用它的人都会完完整整的输入绝对路径,因为还有相对路径和环境变量这些东西,用他们也可以构造出一个文件的路径,这时就要用其他方法来解析了。于是霍然开朗了。
你不在地铁里吃东西,并不能以此就来幻想别人不在那里吃热干面。

alsa-lib/src/userfile.c

点击(此处)折叠或打开

  1. 34
  2.  35 #ifdef HAVE_WORDEXP_H
  3.  36 #include <wordexp.h>
  4.  37 #include <assert.h>
  5.  38 int snd_user_file(const char *file, char **result)
  6.  39 {
  7.  40 wordexp_t we;
  8.  41 int err;
  9.  42
  10.  43 assert(file && result);
  11.  44 err = wordexp(file, &we, WRDE_NOCMD);
  12.  45 switch (err) {
  13.  46 case WRDE_NOSPACE:
  14.  47 return -ENOMEM;
  15.  48 case 0:
  16.  49 if (we.we_wordc == 1)
  17.  50 break;
  18.  51 /* fall thru */
  19.  52 default:
  20.  53 wordfree(&we);
  21.  54 return -EINVAL;
  22.  55 }
  23.  56 *result = strdup(we.we_wordv[0]);
  24.  57 if (*result == NULL)
  25.  58 return -ENOMEM;
  26.  59 wordfree(&we);
  27.  60 return 0;
  28.  61 }
  29.  62
  30.  63 #else /* !HAVE_WORDEXP_H */
  31.  64 /* just copy the string - would be nicer to expand by ourselves, though... */
  32.  65 int snd_user_file(const char *file, char **result)
  33.  66 {
  34.  67 *result = strdup(file);
  35.  68 if (! *result)
  36.  69 return -ENOMEM;
  37.  70 return 0;
  38.  71 }
  39.  72 #endif /* HAVE_WORDEXP_H */




参考连接:
http://blog.chinaunix.net/uid-24774106-id-3237465.html
 
阅读(3066) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~