osパッケージのCreate, NewFile, Open, OpenFile違いについて
Open,CreateはOpenFileの省略形
go/src/os/file.go
func Open(name string) (file *File, err error) {
return OpenFile(name, O_RDONLY, 0)
}
func Create(name string) (file *File, err error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
OpenFileは実装で異なる
$ grep "func OpenFile" . -r
./file_windows.go:func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
./file_unix.go:func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
./file_plan9.go:func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
go/src/os/file_unix.go
func OpenFile(name string, flag int, perm FileMode) (file *File, err error) {
r, e := syscall.Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
if e != nil {
return nil, &PathError{"open", name, e}
}
// There's a race here with fork/exec, which we are
// content to live with. See ../syscall/exec_unix.go.
if !supportsCloseOnExec {
syscall.CloseOnExec(r)
}
return NewFile(uintptr(r), name), nil
}
NewFileはさらに低レベルな処理
$ grep "func NewFile" . -r
./file_windows.go:func NewFile(fd uintptr, name string) *File {
./file_unix.go:func NewFile(fd uintptr, name string) *File {
./file_plan9.go:func NewFile(fd uintptr, name string) *File {
go/src/os/file_unix.go
func NewFile(fd uintptr, name string) *File {
fdi := int(fd)
if fdi < 0 {
return nil
}
f := &File{&file{fd: fdi, name: name}}
runtime.SetFinalizer(f.file, (*file).close)
return f
}
参考
os - The Go Programming Language
https://golang.org/pkg/os/
build-web-application-with-golang/07.5.md at master · astaxie/build-web-application-with-golang
https://github.com/astaxie/build-web-application-with-golang/blob/master/ja/07.5.md