简体   繁体   中英

Is it possible to implement readdir() in Ubuntu 12.10 (kernel 3.5)?

In 8.6 of K & R , the authors implemented a simple version of readdir() . The code is as follows:

#include <sys/dir.h>   /* local directory structure */
/* readdir:  read directory entries in sequence */
Dirent *readdir(DIR *dp)
{
   struct direct dirbuf;  /* local directory structure */
   static Dirent  d;      /* return: portable structure */
   while (read(dp->fd, (char *) &dirbuf, sizeof(dirbuf))
                   == sizeof(dirbuf)) {
       if (dirbuf.d_ino == 0) /* slot not in use */
           continue;
       d.ino = dirbuf.d_ino;
       strncpy(d.name, dirbuf.d_name, DIRSIZ);
       d.name[DIRSIZ] = '\0';  /* ensure termination */
       return &d;
   }
   return NULL;
}

In my opinion, in the line with read() , dp->fd is the file descriptor of the directory. The authors used read() to get struct direct directly from the directory file.

However, in Ubuntu, it is not possible to read a directory file. When I tried to read a directory, I just got something strange.

I read in APUE that in some systems, this action is not allowed. So is there any other ways to realize my own readdir() ?

You are looking at code from 40 years ago. Directories are simply not implemented like that on any modern platform. Read the documentation for your filesystem (ext4 if you are on Linux) if you really need to write code to manipulate it.

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