Linux/ Open directory as a file
Nachiket's answer is correct (as indeed is sujin) but they don't clear up the mystery as to why open
works and not read
. Out of curiosity I made some changes to the given code to find out exactly what was going on.
#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;}
The result of compiling and running this:
file descriptor is 3n = -1read failure 21cannot read: Is a directory
That settles it, though I'd have expected open
to fail, since the correct system function for opening directories is opendir()
.
Though everything in unix is a file (directory also) but still filetype is concept is present in unix and applicable to all files.there are file types like regular file,directory etc and certain operations and functions are allowed/present for every file type.
In your case readdir is applicable for reading contents of directory.