利用Go語言追加內容到檔案末尾_Golang

來源:互聯網
上載者:User

前言

我研究了file庫,終於讓我找到了利用Go語言追加內容到檔案末尾的辦法

主要的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越來越好用!以上就是這篇文章的全部內容,希望對大家的學習或者工作能有所協助,如果有疑問大家可以留言交流。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.