I am trying to figure out a way to declare an empty variable to store the return values of os.Create
and os.Open
. Code:
func main() {
var path = "list.txt"
// Some attempts:
// var file File{}
// var file *File
// Check if file exists
var _, err = os.Stat(path)
// If new file, create it
if os.IsNotExist(err) {
var file, err = os.Create(path)
// If file exists, open it
} else {
var file, err = os.Open(path)
}
// Check errors opening and creating file
if err != nil {
log.Fatal(err)
return
}
// Defer closing file
defer file.Close()
}
Both attempts result in the following error:
./main.go:13: undefined: File
I'm sure this is one of those things that I don't know I don't know. What I do know:
os/file.go
, type of the return value I'm looking for is *File
os/file_unix.go
as a structCan someone explain to me:
os.Create
and os.Open
.Defining variable is var <variable-name> <type>
, learn more about variables.
var file *os.File
var err error
Your updated code:
func main() {
path := "list.txt"
var file *os.File
var err error
// Check if file exists
if err = os.Stat(path); os.IsNotExist(err) {
file, err = os.Create(path)
} else { // If file exists, open it
file, err = os.Open(path)
}
// Check errors opening and creating file
if err != nil {
log.Fatal(err)
return
}
// Defer closing file
defer file.Close()
}