to be
a problem slover

go write string to file

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()
赞(2) 打赏
欢迎转载,注明出处:刘世明的博客 » go write string to file

评论 3

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.info/register-person?ref=IXBIAFVY

    binance2周前 (04-01)回复
  2. #2

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

    Binance注册1周前 (04-05)回复
  3. #3

    Your article helped me a lot, is there any more related content? Thanks! https://accounts.binance.com/register-person?ref=IHJUI7TF

觉得文章有用就打赏一下作者

支付宝扫一扫打赏

微信扫一扫打赏