简体   繁体   中英

How can I detect that I open()ed a directory in C, without using stat()?

I've written a simplified "cat" function in C. It is working fine, except when one of my argument is the name of a directory.

As it is an assignement, I'm only allowed to use "open", "read" and "close" functions in my code.

When "-1" is returned by function open(file, O_RDONLY), I call function ft_display_error to display error messages such as "No such file or directory".

Yet it doesn't work when "file" is a directory: in this case open will not return "-1". It will go on some kind of infinite loop.

void ft_display_file(char *file)
{
    int fd;
    char buf[BUF_SIZE + 1];
    int ret;

    fd = open(file, O_RDONLY);
    if (fd == -1)
        ft_display_error(file);
    else
    {
        ret = read(fd, buf, BUF_SIZE);
        while(ret)
        {
            buf[ret] = 0;
            write(1, buf, ret);
            ret = read(fd, buf, BUF_SIZE);
        }
    }
    close(fd);
}

int main(int ac, char **av)
{
    int i;

    i = 1;
    while (i < ac)
    {
        ft_display_file(av[i]);
        i++;
    }
}

Instead, I would like my program to identify that my argument is a directory, and then display the following message "cat: file: Is a directory.

Opening a directory for reading with open is the low level way of accessing its contents. Not very useful for you, but it doesn't allow to test for a directory.

If you cannot use stat (which is the best option) there seems to be another trick:

According to the documentation of open

The open() function shall fail if:

...

EISDIR The named file is a directory and oflag includes O_WRONLY or O_RDWR.

So first try to open your file with O_RDWR (read-write) and if it fails, check if errno is equal to EISDIR

Code (untested)

fd = open(file, O_RDWR);
if ((fd == -1) && (errno == EISDIR))
{
   // this is a directory
}

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