【问题标题】:C language: error: ‘O_DIRECTORY’ undeclared and accessing files in directory and sub-directory(without using opendir())C语言:错误:'O_DIRECTORY'未声明并访问目录和子目录中的文件(不使用opendir())
【发布时间】:2019-05-10 15:05:38
【问题描述】:

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

【问题讨论】:

  • 你是怎么编译的?如果你这样做 -std=c11 似乎 only O_DIRECTORY 丢失了。
  • 另外,errno 的定义错误,您必须包含&lt;errno.h&gt; 才能正确! “如果为了访问实际对象而禁止宏定义,或者程序定义了名称为 errno 的标识符,则行为未定义。”

标签: c file operating-system directory system-calls


【解决方案1】:

引用holy scripture

O_CLOEXECO_DIRECTORYO_NOFOLLOW 标志不是 在 POSIX.1-2001 中指定,但在 POSIX.1-2008。从 glibc 2.12 开始,可以通过使用值定义 _POSIX_C_SOURCE 来获得它们的定义 大于或等于 200809L_XOPEN_SOURCE 并带有 值大于或等于700。在 glibc 2.11 及更早版本中,通过定义 _GNU_SOURCE 来获取定义。


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2016-08-17
    • 2021-08-25
    • 2017-01-24
    • 2012-03-11
    • 2013-05-19
    相关资源
    最近更新 更多