首页 文章

C语言:错误:'O_DIRECTORY'未声明并访问目录和子目录中的文件(不使用opendir())

提问于
浏览
0

我想循环遍历所有子目录并获取目录和子目录中的所有文件 . 我只想使用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会这样做,但我正在寻找一种不使用它的方法 . 任何帮助,将不胜感激 .

1 回答

  • 1

    引用holy scripture

    POSIX.1-2001中未指定O_CLOEXEC,O_DIRECTORY和O_NOFOLLOW标志,但在POSIX.1-2008中指定 . 由于glibc 2.12,可以通过定义大于或等于200809L的_POSIX_C_SOURCE或大于或等于700的_XOPEN_SOURCE来获得它们的定义 . 在glibc 2.11和更早版本中,通过定义_GNU_SOURCE获得定义 .


    尝试使用 -D_POSIX_C_SOURCE=200809L 进行编译或在包含任何 Headers 之前添加 #define _POSIX_C_SOURCE 200809L .

相关问题