golang追加内容到文件末尾

golang读写文件,网上很多教程了
但是今天有个需求,想要把内容追加写到文件末尾
google了好久,没有查到
研究了一会儿file库,终于让我找到(蒙到)了追加的办法
最主要的2个函数:

func (f *File) Seek(offset int64, whence int) (ret int64, err error)
func (f *File) WriteAt(b []byte, off int64) (n int, err error)

  • Seek()查到文件末尾的偏移量
  • WriteAt()则从偏移量开始写入

以下是栗子:

// fileName:文件名字(带全路径)
// content: 写入的内容
func appendToFile(fileName string, content string) error {
   // 以只写的模式,打开文件
   f, err := os.OpenFile(fileName, os.O_WRONLY, 0644)
   if err != nil {
      fmt.Println("cacheFileList.yml file create failed. err: " + err.Error())
   } else {
      // 查找文件末尾的偏移量
      n, _ := f.Seek(0, os.SEEK_END)
      // 从末尾的偏移量开始写入内容
      _, err = f.WriteAt([]byte(content), n)
   }   
defer f.Close()   
return err}

拿去用吧,别客气 :)
觉得目前国内golang的文档博客还是稍微缺乏了点,
希望大家平时coding中有什么心得体会互相分享,
让golang越来越好用!

2016/08/31 记:
我就是笨蛋,明明最简单的方式就可以实现了:
f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_APPEND, 0666)
以写跟追加的方式打开文件。。。

以上

Just do IT!

    原文作者:Lucas_Ye
    原文地址: https://www.jianshu.com/p/86e12c9c0363
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞