Skip to content

Instantly share code, notes, and snippets.

@scottcagno
Created September 24, 2015 02:18
Show Gist options
  • Select an option

  • Save scottcagno/c33bae38341d50fb1e32 to your computer and use it in GitHub Desktop.

Select an option

Save scottcagno/c33bae38341d50fb1e32 to your computer and use it in GitHub Desktop.
Open / Create File
package main
import (
"log"
"os"
"path"
)
func main() {
fd := Open("a/b/c/d.txt")
if _, err := fd.Write([]byte("This is a test.\nThis is only a test.\n")); err != nil {
log.Fatal(err)
}
if err := fd.Close(); err != nil {
log.Fatal(err)
}
}
// open a file; create path and file if not exist, else return file descriptor
func Open(filepath string) *os.File {
// split path and file from filepath
dir, file := path.Split(filepath)
// if there are any nested directories...
if dir != "" {
// check to see if directories already exist...
if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
log.Println("Creating all dirs:", dir)
// if not, make all nested directories...
if err := os.MkdirAll(dir, 0755); err != nil {
log.Fatal(err)
}
}
log.Println("Directory exists:", dir)
}
// if the file param isn't empty...
if file != "" {
// check to see if file already exists...
if _, err := os.Stat(filepath); err != nil && os.IsNotExist(err) {
log.Println("Creating file:", filepath)
// if not, create file...
if _, err := os.Create(filepath); err != nil {
log.Fatal(err)
}
}
log.Println("File exists:", file)
}
// all directories and files should exist, or have been created by now
fd, err := os.OpenFile(filepath, os.O_APPEND|os.O_RDWR, 0644)
if err != nil {
log.Fatal(err)
}
if err := fd.Sync(); err != nil {
log.Fatal(err)
}
log.Println("Opening and return file:", fd.Fd())
// return file descriptor
return fd
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment