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.
12 // Auxiliary information if the File describes a directory
14 buf
[]byte // buffer for directory I/O
15 dir
*syscall
.DIR
// from opendir
18 // DevNull is the name of the operating system's ``null device.''
19 // On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
20 const DevNull
= "/dev/null"
22 // Open opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.)
23 // if applicable. If successful, methods on the returned File can be used for I/O.
24 // It returns the File and an Error, if any.
25 func Open(name
string, flag
int, perm
uint32) (file
*File
, err Error
) {
26 r
, e
:= syscall
.Open(name
, flag|syscall
.O_CLOEXEC
, perm
)
28 return nil, &PathError
{"open", name
, Errno(e
)}
31 // There's a race here with fork/exec, which we are
32 // content to live with. See ../syscall/exec.go
33 if syscall
.O_CLOEXEC
== 0 { // O_CLOEXEC not supported
34 syscall
.CloseOnExec(r
)
37 return NewFile(r
, name
), nil
40 // Close closes the File, rendering it unusable for I/O.
41 // It returns an Error, if any.
42 func (file
*File
) Close() Error
{
43 if file
== nil || file
.fd
< 0 {
47 if e
:= syscall
.Close(file
.fd
); e
!= 0 {
48 err
= &PathError
{"close", file
.name
, Errno(e
)}
50 file
.fd
= -1 // so it can't be closed again
52 // no need for a finalizer anymore
53 runtime
.SetFinalizer(file
, nil)
57 // Stat returns the FileInfo structure describing file.
58 // It returns the FileInfo and an error, if any.
59 func (file
*File
) Stat() (fi
*FileInfo
, err Error
) {
60 var stat syscall
.Stat_t
61 e
:= syscall
.Fstat(file
.fd
, &stat
)
63 return nil, &PathError
{"stat", file
.name
, Errno(e
)}
65 return fileInfoFromStat(file
.name
, new(FileInfo
), &stat
, &stat
), nil
68 // Readdir reads the contents of the directory associated with file and
69 // returns an array of up to count FileInfo structures, as would be returned
70 // by Lstat, in directory order. Subsequent calls on the same file will yield
72 // A negative count means to read until EOF.
73 // Readdir returns the array and an Error, if any.
74 func (file
*File
) Readdir(count
int) (fi
[]FileInfo
, err Error
) {
80 names
, err1
:= file
.Readdirnames(count
)
84 fi
= make([]FileInfo
, len(names
))
85 for i
, filename
:= range names
{
86 fip
, err
:= Lstat(dirname
+ filename
)
87 if fip
== nil || err
!= nil {
88 fi
[i
].Name
= filename
// rest is already zeroed out
96 // Truncate changes the size of the named file.
97 // If the file is a symbolic link, it changes the size of the link's target.
98 func Truncate(name
string, size
int64) Error
{
99 if e
:= syscall
.Truncate(name
, size
); e
!= 0 {
100 return &PathError
{"truncate", name
, Errno(e
)}