【问题标题】:Go code to list files in a Linux directory using getdents()Go 代码使用 getdents() 列出 Linux 目录中的文件
【发布时间】:2014-09-21 05:58:06
【问题描述】:

作为练习,我想将一些使用许多系统调用的 C 代码翻译成 Golang。我在 Unix 和 Linux StackExchange 上找到了这个 nice code example:

/*
 * List directories using getdents() because ls, find and Python libraries
 * use readdir() which is slower (but uses getdents() underneath.
 *
 * Compile with 
 * ]$ gcc  getdents.c -o getdents
 */
#define _GNU_SOURCE
#include <dirent.h>     /* Defines DT_* constants */
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>

#define handle_error(msg) \
       do { perror(msg); exit(EXIT_FAILURE); } while (0)

struct linux_dirent {
   long           d_ino;
   off_t          d_off;
   unsigned short d_reclen;
   char           d_name[];
};

#define BUF_SIZE 1024*1024*5

int
main(int argc, char *argv[])
{
   int fd, nread;
   char buf[BUF_SIZE];
   struct linux_dirent *d;
   int bpos;
   char d_type;

   fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY);
   if (fd == -1)
       handle_error("open");

   for ( ; ; ) {
       nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
       if (nread == -1)
           handle_error("getdents");

       if (nread == 0)
           break;

       for (bpos = 0; bpos < nread;) {
           d = (struct linux_dirent *) (buf + bpos);
           d_type = *(buf + bpos + d->d_reclen - 1);
           if( d->d_ino != 0 && d_type == DT_REG ) {
              printf("%s\n", (char *)d->d_name );
           }
           bpos += d->d_reclen;
       }
   }

   exit(EXIT_SUCCESS);
}

我只能使用ioutil.ReadDir 对此进行编码,这违背了目的。有人知道如何翻译这个吗?

【问题讨论】:

  • 您是否正在尝试解决具体问题?如果您想低于 ioutil 的级别,请使用 os.File.Readdirnames(它使用 syscall 包中最低级别的 getdents)。检查 os 包源以获取提示(以 file_unix.go 和 dir_unix.go 开头)。
  • 我被缓冲区管理困住了。 dir_unix.go 有很大帮助!谢谢+1

标签: c linux go system-calls


【解决方案1】:

我会避免使用此代码。正如所写,这是错误的:在 32 位系统甚至一些 64 位系统上,SYS_getdents 是不提供 d_type 并且缺乏对 64 位 inode 编号的支持的遗留系统调用,这意味着你得到了免费的现代文件系统上的错误。即使你修复它,它也比内联readdir 好不了多少,它在内部做的事情基本上完全一样。

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
  • 我认为“你不应该这样做,而且你的问题是基于你应该这样做的错误前提”是对此类问题的合理答案,只要答案提供了一些解释为什么会这样。
  • 我不认为这是一个坏建议,但我认为这个答案对于所提出的问题来说太短了。来自常见问题解答:“答案可以是“不要那样做”,但也应该包括“试试这个”。我认为这在询问的人(以及未来的人也在搜索?)清楚地表明他们是语言新手的情况下很有用,因此您提供的细节可能不足以在经验曲线的这一点上对他们有用。
  • “试试这个”显然只是使用 readlink 或任何等效的 Go 提供的。我同意我的答案可能不是这个答案的最佳、最详细的版本,但我也不认为它不适合作为答案。
  • “最高效”的 Go 版本 (os.File.Readdir()) 的问题是它强制为每个文件执行 stat(2) 系统调用。在许多情况下,这不是必需的,因为dirent 结构的d_type 字段可以提供足够的信息。这就是为什么在 Go 中一个简短的 find 克隆会比 find 慢。如果有人想复制 Go 标准库代码并使其在没有统计信息的情况下工作,那么它的速度差不多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2019-12-04
  • 2011-01-23
  • 2012-12-09
相关资源
最近更新 更多