标题很清楚:Is it safe to use basename
(man 3 basename
) with __FILE__
?.
它编译并且似乎工作正常,但是basename
的参数是char*
(不是const char*
) 和 man
-page 说:
Both dirname() and basename() may modify the contents of path, so it may be desirable to pass a copy when calling one of these functions.
所以,这让我很担心。
也许问题应该更像是:__FILE__
的类型是什么?不就是字符串字面量/const char*
吗?但如果是,为什么没有编译时错误(const char*
到 char*
)?
最佳答案
仔细阅读 basename(3)并注意:
Warning: there are two different functions
basename()
- see below.
并注意NOTES
There are two different versions of
basename()
- the POSIX version described above, and the GNU version, which one gets after#define _GNU_SOURCE /* See feature_test_macros(7) */ #include <string.h>
The GNU version never modifies its argument, and returns the empty string when path has a trailing slash
(重点是我的)
因为据说GNU版本不修改它的参数,使用它是安全的__FILE__
顺便说一句,您可以考虑自定义您的 GCC(例如使用 MELT )来定义一些 __builtin_basename
如果给定一个像 __FILE__
这样的字符串文字,它将在编译时计算基本名称> 或者在运行时调用 basename
。
注意 libgen.h
有 #define basename __xpg_basename
关于c++ - 将 `basename` 与 __FILE__ 一起使用是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38593014/