github.com/criyle/go-sandbox@v0.10.3/cmd/runprog/fileutil.go (about) 1 package main 2 3 import "os" 4 5 // prepareFile opens file for new process 6 func prepareFiles(inputFile, outputFile, errorFile string) ([]*os.File, error) { 7 var err error 8 files := make([]*os.File, 3) 9 if inputFile != "" { 10 files[0], err = os.OpenFile(inputFile, os.O_RDONLY, 0755) 11 if err != nil { 12 goto openerror 13 } 14 } 15 if outputFile != "" { 16 files[1], err = os.OpenFile(outputFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755) 17 if err != nil { 18 goto openerror 19 } 20 } 21 if errorFile != "" { 22 files[2], err = os.OpenFile(errorFile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0755) 23 if err != nil { 24 goto openerror 25 } 26 } 27 return files, nil 28 openerror: 29 closeFiles(files) 30 return nil, err 31 } 32 33 // closeFiles close all file in the list 34 func closeFiles(files []*os.File) { 35 for _, f := range files { 36 if f != nil { 37 f.Close() 38 } 39 } 40 }