-1

I was wondering how to do this. I have tried several things but nothing seems to work for me. I don't want to use opendir() syscall nor do i want to use readdir() system call. Could you please tell me how to do this because i get garbage values. I want to list files that are inside a folder. I get garbage value stored in the buffer from this code.

char buffer[16];
    size_t offset = 0;
    size_t bytes_read;
    
    int i;
    /* Open the file for reading. */
    int fd = open ("testfolder", O_RDONLY);
    /* Read from the file, one chunk at a time. Continue until read
    “comes up short”, that is, reads less than we asked for.
    This indicates that we’ve hit the end of the file. */
    do {
        /* Read the next line’s worth of bytes. */
        bytes_read = read (fd, buffer, 16);
        /* Print the offset in the file, followed by the bytes themselves.*/
        
        // printf ("0x%06lx : ", offset);
        // for (i = 0; i < bytes_read; ++i)
        // printf ("%02x ", buffer[i]);
        printf("%s", buffer);
        printf ("\n");
        /* Keep count of our position in the file. */
        // offset += bytes_read;
    }
    while (bytes_read!=-1);
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
user648933
  • 25
  • 3

1 Answers1

4

You can't do this. The kernel only allows open on a directory with special options, and it doesn't allow read on a directory at all. You have to use opendir and readdir.

(Under the hood, opendir calls open with those special options I mentioned, and readdir calls the private system call getdents. See https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/opendir.c and https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/readdir.c . Doing this yourself is not recommended.)

zwol
  • 135,547
  • 38
  • 252
  • 361