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

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

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

支付宝扫一扫打赏

微信扫一扫打赏