源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

利用Go语言追加内容到文件末尾

  • 时间:2022-02-25 00:43 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:利用Go语言追加内容到文件末尾
[b]前言[/b] 我研究了file库,终于让我找到了利用Go语言追加内容到文件末尾的办法 [b]主要的2个函数:[/b]
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
[code]Seek()[/code]查到文件末尾的偏移量 [code]WriteAt()[/code]则从偏移量开始写入 [b]以下是例子:[/b]
// 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}
[b]总结[/b] 小编觉得目前国内golang的文档博客还是稍微缺乏了点,希望大家平时coding中有什么心得体会互相分享,让golang越来越好用!以上就是这篇文章的全部内容,希望对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。  
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部