Q: C语言中定义的__FILE__使用,如何只出现该文件名,而不显示路径
A:
可以用宏定义来实现去除文件名中的路du径名。
因为windows和linux下,文zhi件名中的路径分隔符号不同,windows中是dao"/",而linux中是"/",所以,采用的宏不同:
#include <string.h> //strrchr()函数所需头文件
windows:
#define filename(x) strrchr(x,'\\')?strrchr(x,'\\')+1:x
linux:
#define filename(x) strrchr(x,'/')?strrchr(x,'/')+1:x
调用:
printf("filename:%s\n", filename(__FILE__) );
相关函数说明:
函数原型:char *strrchr(const char *s, int c);
函数功能:The strrchr() function returns a pointer to the last occurrence of the character 【c】 in the string 【s】.函数返回一个指向最后一次出现在字符串s中的字符c的位置指针,如果c不在s中,返回NULL。
PS:linux中提供了相应的函数:basename(s),用来获取不带路径的文件名。