C language: error: ‘O_DIRECTORY’ undeclared and accessing files in directory and sub-directory(without using opendir())

C language: error: ‘O_DIRECTORY’ undeclared and accessing files in directory and sub-directory(without using opendir())

我想遍历所有的子目录,获取目录和子目录下的所有文件。 我只想使用 open() 和 read() 系统调用来这样做(不是 opendir() 或 is_dir) 我一直收到错误

error: ‘O_DIRECTORY’ undeclared (first use in this function)

虽然我确实导入了 fcntl。

下面是我的代码:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include<fcntl.h> 
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
extern int errno; 

int main()
{
    int fd;
    if ((fd = open(".", O_DIRECTORY | O_RDONLY)) ==-1)
    {
        printf("error %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

此外,如何使用 read() 系统调用来检查我正在读取的是文件还是子目录? (正如我提到的,我还想查看所有子目录中的文件) 我知道 is_dir 会这样做,但我正在寻找一种不使用它的方法。 任何帮助将不胜感激。

引用 holy scripture:

The O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW flags are not specified in POSIX.1-2001, but are specified in POSIX.1-2008. Since glibc 2.12, one can obtain their definitions by defining either _POSIX_C_SOURCE with a value greater than or equal to 200809L or _XOPEN_SOURCE with a value greater than or equal to 700. In glibc 2.11 and earlier, one obtains the definitions by defining _GNU_SOURCE.


尝试使用 -D_POSIX_C_SOURCE=200809L 进行编译或在包含任何 headers.

之前添加 #define _POSIX_C_SOURCE 200809L