12
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

Create,NewFile,Open,OpenFileの違い

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
12
Help us understand the problem. What are the problem?