仅在 POSIX 上打开文件
Open for Files Only on POSIX
众所周知,在 C 中调用 open()
将 return 一个文件描述符,给定一个 pathname
和可选的 flags
。
int fd;
if ((fd = open(pathname, O_RDONLY)) == -1) {
printf("Could not open file\n");
return;
}
在 man page for open()
中定义了标志 O_DIRECTORY
,其中:
If pathname is not a directory, cause the open to fail. This
flag was added in kernel version 2.1.126, to avoid denial-of-
service problems if opendir(3) is called on a FIFO or tape
device.
但我似乎找不到像 O_FILE
这样的东西,这会导致 open()
在目录而不是文件上失败。
是否有这样的标志可以传递给 open()
或其他确定 pathname
是否为文件的方法,而不是调用 stat()
?
不,没有这样的标志。 stat
函数也是不可接受的,因为它有竞争条件。 (一般来说,你应该只调用 stat
本身,而不是与 open
结合使用。)
您的选择是:
使用fstat
.
打开文件进行写入,其中returnsEISDIR
用于目录。
调用 read
,其中 returns EISDIR
用于目录。
众所周知,在 C 中调用 open()
将 return 一个文件描述符,给定一个 pathname
和可选的 flags
。
int fd;
if ((fd = open(pathname, O_RDONLY)) == -1) {
printf("Could not open file\n");
return;
}
在 man page for open()
中定义了标志 O_DIRECTORY
,其中:
If pathname is not a directory, cause the open to fail. This flag was added in kernel version 2.1.126, to avoid denial-of- service problems if opendir(3) is called on a FIFO or tape device.
但我似乎找不到像 O_FILE
这样的东西,这会导致 open()
在目录而不是文件上失败。
是否有这样的标志可以传递给 open()
或其他确定 pathname
是否为文件的方法,而不是调用 stat()
?
不,没有这样的标志。 stat
函数也是不可接受的,因为它有竞争条件。 (一般来说,你应该只调用 stat
本身,而不是与 open
结合使用。)
您的选择是:
使用
fstat
.打开文件进行写入,其中returns
EISDIR
用于目录。调用
read
,其中 returnsEISDIR
用于目录。