Linux/ Open directory as a file

c, filesystems, gnu, linux, unix

Solution

Files are also called `regular files` to distinguish them from `special files`.

Directory or not a `regular file`. The most common `special file` is the directory. The layout of a directory file is defined by the filesystem used.

So use opendir to open diretory.

Problem

I've been reading Brian Kernighan and Dennis Ritchie - The C Programming Language and chapter 8.6 is about directory listing under UNIX OS. They say that everything and even directory is a file. This means that I should be able to open directory as a file? I've tried it using stdio functions and it didn't work. Now, I'm trying it with UNIX system functions. Of course, I'm not using UNIX, I'm using 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 writes nothing even when argn is 1 (no parameters) and I'm trying to read current directory. Any ideas/explanations? :)

Original source