简体   繁体   中英

Why doesn't this C code for listing a directory work?

I thought the following C code would list what is in the root directory. Why does it loop forever?

#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct linux_dirent {
  unsigned long d_ino;
  unsigned long d_off;
  unsigned short d_reclen;
  char d_name[];
} linux_dirent;
extern int getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count)
{
    return syscall(SYS_getdents, fd, dirp, count);
}

int main(void)
{
  linux_dirent* entryPtr = malloc(20000000);
  linux_dirent* buffer = entryPtr;
  int fd = open("/", O_RDONLY | O_DIRECTORY);
  int numentries = getdents((unsigned int)fd, entryPtr, 20000000);
  close(fd);
  for(;(entryPtr - buffer) < numentries; entryPtr += entryPtr->d_reclen)
  {
    puts(entryPtr->d_name);
  }
}

(entryPtr - buffer) will return (difference between the pointers) / (sizeof(linux_dirent)), while numentries is in bytes. If you were to use a char ptr and cast it to an entry_ptr it would probably work -- ie

int main(void)
{
  char *entryPtr = malloc(20000000);
  char* buffer = entryPtr;
  int fd = open("/", O_RDONLY | O_DIRECTORY);
  int numentries = getdents((unsigned int)fd, (linux_dirent *)entryPtr, 20000000);
  close(fd);
  for(;(entryPtr - buffer) < numentries; entryPtr += ((linux_dirent *)entryPtr)->d_reclen)
  {
    puts(((linux_dirent *)entryPtr)->d_name);
  }
}

it would likely work. However, I agree that you should be using readdir, not getdents.

It should be

for(;
    (entryPtr - buffer) < numentries; 
    entryPtr = (char*)((entryPtr+1)+entryPtr->d_reclen+2)
   )
 {
   puts(entryPtr->d_name);
 }

The +2 is for the the padding byte and the d_type field

since according to getdents(2) the entries are variable length.

But you really want to use readdir(3) . getdents is only useful to those implementing readdir , like readdir.c from MUSL libc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM