package file
import (
"os"
"path/filepath"
)
func WriteToFile(file string, str string) error{
dir := filepath.Dir(file)
if _, err := os.Stat(dir);os.IsNotExist(err) {
os.MkdirAll(dir, 0755)
}
f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
if _, err = f.WriteString(str + "\n"); err != nil {
return err
}
return f.Sync()
}
context
- write string to file by append
- if file not exists, create it (create dir first then create file by openFile option
os.O_CREATE)
- close file by defer
- commit file change by
f.Sync()
Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.info/register-person?ref=IXBIAFVY
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your article helped me a lot, is there any more related content? Thanks! https://accounts.binance.com/register-person?ref=IHJUI7TF