POSIX fopen(NULL,"r")

KAc*_*ion 3 c io fopen posix

我想知道,如果用NULL文件名调用fopen是合法的.如果是,它为我节省了2行代码.在我的GNU/Linux机器上它可以工作,但它必须是可移植的.我看了POSIX fopen,但它没有说明这个案子.是不确定的行为?

Ale*_*nze 5

从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.
Run Code Online (Sandbox Code Playgroud)

fopen()同一标准中的描述没有提及NULL或根本没有提及null pointer.

因此,根据C标准,传递NULL为文件名字符串指针fopen()导致unefined行为.

但是,POSIX可以扩展行为.