前言
我研究了file庫(kù),終于讓我找到了利用Go語(yǔ)言追加內(nèi)容到文件末尾的辦法
主要的2個(gè)函數(shù):
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: 寫入的內(nèi)容 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) // 從末尾的偏移量開始寫入內(nèi)容 _, err = f.WriteAt([]byte(content), n) } defer f.Close() return err} |
總結(jié)
小編覺(jué)得目前國(guó)內(nèi)golang的文檔博客還是稍微缺乏了點(diǎn),希望大家平時(shí)coding中有什么心得體會(huì)互相分享,讓golang越來(lái)越好用!以上就是這篇文章的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)或者工作能有所幫助,如果有疑問(wèn)大家可以留言交流。