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)
}
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.
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.
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.
📁 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() .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With