环境(centos 6.10):
$ uname -r 2.6.32-754.el6.x86_64
函数定义:
// /usr/include/libgen.h extern char *__xpg_basename (char *__path) __THROW; #define basename __xpg_basename
这个basename函数可以返回路径最后一个路径分隔符之后的内容,
比如basename("/usr/local/abc")
返回 abc
.
调用示例如下:
#include <stdio.h> #include <libgen.h> int main(int argc, char *argv[]) { char* files[] = { "/usr/local/nginx/conf/nginx.conf", "./a.out", "/usr/include/libgen.h", NULL }; char **p = files; while (*p) { printf("basename(\"%s\")=%s\n", *p, basename(*p)); *p++; } return 0; }
编译运行:
$ gcc basename.c $ ./a.out basename("/usr/local/nginx/conf/nginx.conf")=nginx.conf basename("./a.out")=a.out basename("/usr/include/libgen.h")=libgen.h
直观点理解, 就是输出“文件名”。
shell下有个命令, 也叫basename, 用法一样, 示例:
$ for i in /usr/local/nginx/conf/nginx.conf ./a.out /usr/include/libgen.h; do basename $i; done nginx.conf a.out libgen.h
还有个叫dirname
的函数, 也在libgen.h
中:
extern char *dirname (char *__path) __THROW;
dirname用法和basename一样, 不过它返回的是除去"文件名"之外的目录名. 同名的命令dirname
也是同样的功能, 一看就明白:
$ for i in /usr/local/nginx/conf/nginx.conf ./a.out /usr/include/libgen.h; do dirname $i; done /usr/local/nginx/conf . /usr/include
这个dirname命令有个惯用法, 就是获取当前脚本所在路径:
scriptDir=$(cd `dirname $0`; pwd)
这样不管代在哪里执行这个脚本, $scriptDir的值都可以取得你执行时的目录名. 非常实用.
标签:include,basename,c++,nginx,usr,conf,dirname From: https://www.cnblogs.com/opensmarty/p/16847495.html