gpt4 book ai didi

c - 仅在 POSIX 上打开文件

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:54 25 4
gpt4 key购买 nike

众所周知,在 C 中调用 open() 将返回一个文件描述符,给定一个 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 函数也是 Not Acceptable ,因为它有竞争条件。 (一般来说,你应该只调用 stat 本身,而不是与 open 一起调用。)

您的选择是:

  1. 使用fstat

  2. 打开文件进行写入,返回目录的 EISDIR

  3. 调用 read,返回目录的 EISDIR

关于c - 仅在 POSIX 上打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40968911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com