OSDN Git Service

c693aebf3775861334f170c879a62e727ee99df5
[pf3gnuchains/gcc-fork.git] / libgo / go / os / dir.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package os
6
7 import (
8         "io"
9         "syscall"
10         "unsafe"
11 )
12
13 //extern opendir
14 func libc_opendir(*byte) *syscall.DIR
15
16 //extern closedir
17 func libc_closedir(*syscall.DIR) int
18
19 // FIXME: pathconf returns long, not int.
20 //extern pathconf
21 func libc_pathconf(*byte, int) int
22
23 func clen(n []byte) int {
24         for i := 0; i < len(n); i++ {
25                 if n[i] == 0 {
26                         return i
27                 }
28         }
29         return len(n)
30 }
31
32 var elen int
33
34 func (file *File) readdirnames(n int) (names []string, err error) {
35         if elen == 0 {
36                 var dummy syscall.Dirent
37                 elen = (int(unsafe.Offsetof(dummy.Name)) +
38                         libc_pathconf(syscall.StringBytePtr(file.name), syscall.PC_NAME_MAX) +
39                         1)
40         }
41
42         if file.dirinfo == nil {
43                 file.dirinfo = new(dirInfo)
44                 file.dirinfo.buf = make([]byte, elen)
45                 file.dirinfo.dir = libc_opendir(syscall.StringBytePtr(file.name))
46         }
47
48         entry_dirent := unsafe.Pointer(&file.dirinfo.buf[0]).(*syscall.Dirent)
49
50         size := n
51         if size < 0 {
52                 size = 100
53                 n = -1
54         }
55
56         names = make([]string, 0, size) // Empty with room to grow.
57
58         dir := file.dirinfo.dir
59         if dir == nil {
60                 return names, NewSyscallError("opendir", syscall.GetErrno())
61         }
62
63         for n != 0 {
64                 var result *syscall.Dirent
65                 i := libc_readdir_r(dir, entry_dirent, &result)
66                 if i != 0 {
67                         return names, NewSyscallError("readdir_r", i)
68                 }
69                 if result == nil {
70                         break // EOF
71                 }
72                 var name = string(result.Name[0:clen(result.Name[0:])])
73                 if name == "." || name == ".." { // Useless names
74                         continue
75                 }
76                 names = append(names, name)
77                 n--
78         }
79         if n >= 0 && len(names) == 0 {
80                 return names, io.EOF
81         }
82         return names, nil
83 }