【发布时间】: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