Linux / Open directory as a file

I read Brian Kernighan and Dennis Ritchie - The C Programming Language, and chapter 8.6 lists directories under UNIX OS. They say that everything and even the directory is a file. Does this mean that I have to open the directory as a file? I tried this with stdio functions and it did not work. Now I'm trying to work with UNIX system functions. Of course, I do not use UNIX, I use Ubuntu linux. Here is my code:

#include <syscall.h>
#include <fcntl.h>

int main(int argn, char* argv[]) {
    int fd;
    if (argn!=1) fd=open(argv[1],O_RDONLY,0);
    else fd=open(".",O_RDONLY,0);
    if (fd==-1) return -1;

    char buf[1024];
    int n;
    while ((n=read(fd,buf,1024))>0)
        write(1,buf,n);

    close (fd);
    return 0;
}

This does not write anything, even when argn is 1 (without parameters), and I'm trying to read the current directory. Any ideas / explanations? :)

+4
source share
5 answers

regular files, special files.

regular file. special file . .

opendir, .

+2

unix - (), - unix . , , .., / .

readdir .

+2

( ), , open , read. , , .

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char* argv[]) {
    int fd = -1;
    if (argc!=1) fd=open(argv[1],O_RDONLY,0);
    else fd=open(".",O_RDONLY,0);
    if (fd < 0){
      perror("file open");
      printf("error on open = %d", errno);
      return -1;
    }
    printf("file descriptor is %d\n", fd);

    char buf[1024];
    int n;
    if ((n=read(fd,buf,1024))>0){
        write(1,buf,n);
    }
    else {
      printf("n = %d\n", n);
      if (n < 0) {
        printf("read failure %d\n", errno);
        perror("cannot read");
      }
    }
    close (fd);
    return 0;
}

:

file descriptor is 3
n = -1
read failure 21
cannot read: Is a directory

, , open , - opendir().

+2

K & R UNIX. , , UNIX 14 . opendir(), readdir(),... , ( 1990 )

0

Source: https://habr.com/ru/post/1524059/


All Articles