c++ - 将 `basename` 与 __FILE__ 一起使用是否安全?

标签 c++ c posix

标题很清楚: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/

相关文章:

c# - 为什么 CLS 要求抛出/捕获异常派生对象?

c - 在初始化互斥量时在简单的生产者消费者示例中出错

在 C 中复制一个带有字符串成员的结构

c++ - 如何将信号名称(字符串)转换为信号代码?

c - SIGINT 信号后进程终止

c++ - C++ 新手,签名定义

c# - 为控制台应用程序制作 UI

c++ - 工厂模式在编译时分配内存,以及如何打印编译时信息

c - 尝试将短整型写入缓冲区开始会产生奇怪的输出

c - Makefile目标文件生成、变量替换等问题