I'm trying to create a directory using os.Mkdir()
and then create files in it, similar to this script:
package main
import (
"log"
"os"
"path"
)
func main() {
dir := "test_dir"
os.Mkdir(dir, os.ModeDir)
fileName := path.Join(dir, "file.txt")
_, err := os.Create(fileName)
if err != nil {
log.Fatalf("create file: %v", err)
}
}
However, if I run this, I get
> go run fileperms.go
2019/10/15 14:44:02 create file: open test_dir/file.txt: permission denied
exit status 1
It is not immediately clear to me from https://golang.org/pkg/os/#FileMode how to specify the FileMode
in order to allow the same script to create files in the newly-created directory. How can I achieve this?
I found that I am able to create files in the directory if I set the permission to 0777
:
package main
import (
"io/ioutil"
"os"
"path"
)
func main() {
dir := "test_dir"
os.Mkdir(dir, 0777)
fileName := path.Join(dir, "file.txt")
ioutil.WriteFile(fileName, []byte("foobar"), 0666)
}
Now the file is created with the expected content:
> cat test_dir/file.txt
foobar⏎