LoginSignup
14
12

More than 5 years have passed since last update.

Create,NewFile,Open,OpenFileの違い

Last updated at Posted at 2015-08-01

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

14
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12