Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang os.Create cause "no such file or directory" error

Tags:

file

go

Must be something simple, but I cannot seem to figure out. I keep getting "no such file or directory" error. Thought the Create function is to create a new file?

package main

import (
    "log"
    "os"
)

func main() {
    f, err := os.Create("~/golang-server.log")
    defer f.Close()
    if err != nil {
        panic(err.Error())
    }
    log.SetOutput(f)
}
like image 786
Bruce Avatar asked Apr 11 '17 02:04

Bruce


People also ask

How do you solve errors No such file or directory?

In some cases, this error could be shown when the path of the specified file or folders exceeds 258 characters in length. The way to solve this is to reduce the length of the full path to the items specified, either by moving or renaming the file(s) and/or containing folders.

What does os do in Golang?

The os package in Go provides a platform independent interface to work with operating system functionality, such as working with the file system, creating files and directories, and so forth.

How do you check if a path is a file or directory Golang?

In order to check if a particular file exists inside a given directory in Golang, we can use the Stat() and the isNotExists() function that the os package of Go's standard library provides us with. The Stat() function is used to return the file info structure describing the file.

How do you use mkdir in Golang?

📁 Create a directory in Go To create a single directory in Go, use the os. Mkdir() function. If you want to create a hierarchy of folders (nested directories), use os. MkdirAll() .


1 Answers

You can't use ~ or environment variable like $HOME to specify the file path, they're string literal and means actual path. The error you got is because it treat ~/golang-server.log as a relative path of current directory, and there's no directory ~ in current directory.

With manually created sub-directory ~, your code will succeed:

 ~/test/ mkdir \~
 ~/test/ go run t.go
 ~/test/ ls \~
golang-server.log

So need to pass an absolute path or relative path to os.Create.

like image 71
shizhz Avatar answered Nov 15 '22 07:11

shizhz