Standard library / os

os.O_EXCL

Combined with O_CREATE, requires the file not to exist; useful to prevent accidentally overwriting a named file. Example uses a disposable temporary workspace. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
const O_EXCL int = syscall.O_EXCL

Working Example

Example Snippetgo
package main
import (  "errors"  "fmt"  "os")
func check(e error) {  if e != nil {    panic(e)  }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  seed()  _, e := os.OpenFile("a.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)  fmt.Println(errors.Is(e, os.ErrExist))}
Go Reference