前言
我研究了file庫,終于讓我找到了利用Go語言追加內容到文件末尾的辦法
主要的2個函數:
1
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()
則從偏移量開始寫入
以下是例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// 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越來越好用!以上就是這篇文章的全部內容,希望對大家的學習或者工作能有所幫助,如果有疑問大家可以留言交流。