golang讀寫文件赘方,網(wǎng)上很多教程了
但是今天有個需求榜苫,想要把內(nèi)容追加寫到文件末尾
google了好久铝宵,沒有查到
研究了一會兒file庫谦纱,終于讓我找到(蒙到)了追加的辦法
最主要的2個函數(shù):
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: 寫入的內(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}
拿去用吧,別客氣 :)
覺得目前國內(nèi)golang的文檔博客還是稍微缺乏了點跨嘉,
希望大家平時coding中有什么心得體會互相分享川慌,
讓golang越來越好用!
2016/08/31 記:
我就是笨蛋祠乃,明明最簡單的方式就可以實現(xiàn)了:
f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_APPEND, 0666)
以寫跟追加的方式打開文件窘游。。跳纳。
以上
Just do IT忍饰!