简体   繁体   中英

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

I want to loop through all the sub-directories and get all the files in the directory and sub-directories. I only want to use the open() and read() system call to do so(not opendir() or is_dir) bit I keep on getting an error

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

although I did imported the fcntl.

here is my code down below:

#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;
}

In addition how can use the read() system call to check if I'm reading a file or a sub-directory? (as I mentioned I want to go also over the files in all the sub-directories) I know is_dir does that but I'm looking for a way to do it without using it. Any help would be appreciated.

Quoting the 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 .


Try compiling with -D_POSIX_C_SOURCE=200809L or add a #define _POSIX_C_SOURCE 200809L before including any headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM