0

How we can use C functions open/read/close properly in order to read a linux directory?. I notice serveral others asked this question before, about on reading directories in C, also that several ones suggest the use of readdir/opendir/closedir functions, I know, but RnK book (the C programming language) in fact define or introduces those readdir/opendir/closedir/ functions, the problem is that read() function "not read" properly directories; it returns -1 instead of the number of bytes readed. Is there any change into the actual read() C function that produces this or it is necesary modifications to read()?

Here is my example code:

#include <sys/types.h>
#include <unistd.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>


int main(){
int fd;
size_t nbytes;
ssize_t bytes_read;
char buf[20];

fd=open(".",O_RDONLY,0);
nbytes = sizeof(buf);
bytes_read = read(fd, buf, nbytes);
printf("Buf size: %ld file descriptor: %d bytes readed:
%ld\n",nbytes,fd,bytes_read);

}

Compiling above code in ubuntu linux read gives bytes_read = -1. Thanks in advance

  • 1
    Just use `opendir()` etc. – Shawn Oct 06 '19 at 01:58
  • If for whatever reason you can't/won't use `opendir` and `readdir`, you can try `getdents` or `getdents64`. – Steve Summit Oct 06 '19 at 03:07
  • You should check why and *what* is failing first. I'd suggest you catch the ```errno``` number, after both ```open``` and ```read``` calls and see what's failing and why, consult ```open(2)``` and ```read(2)``` man pages. See also https://stackoverflow.com/questions/503878/how-to-know-what-the-errno-means – gstukelj Oct 06 '19 at 16:38
  • Yes, with getdents64 it works!, "man open" and "man read" were useful. Thanks- @gst – Martin Garcia Fernandez Oct 14 '19 at 19:08

0 Answers0