我想知道,使用 NULL 文件名调用 fopen 是否合法。如果是,它为我节省了 2 行代码。在我的 GNU/Linux 机器上它可以工作,但它必须是可移植的。我看了POSIX fopen ,但它没有说明这个案例。这是未定义的行为吗?
最佳答案
从 C 标准(从 1999 年):
7.1.4 库函数的使用
第 1 条:
Each of the following statements applies unless explicitly stated otherwise
in the detailed descriptions that follow: If an argument to a function has an
invalid value (such as a value outside the domain of the function, or a
pointer outside the address space of the program, or a null pointer, or a
pointer to non-modifiable storage when the corresponding parameter is not
const-qualified) or a type (after promotion) not expected by a function with
variable number of arguments, the behavior is undefined.
fopen()
的说明在同一标准中没有提到 NULL
或 null pointer
根本。因此,根据 C 标准,通过
NULL
作为文件名字符串指针指向 fopen()
导致不规范的行为。但是,POSIX 可能会扩展该行为。
关于c - POSIX fopen(NULL ,"r"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12620582/