Appends content to the end of the file using the Go language

  • 2020-06-03 06:46:17
  • OfStack

preface

I researched the file library and finally found a way to append content to the end of a file using the Go language

The two main functions:


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() Look up the offset at the end of the file

WriteAt() Write from the offset

Here are some examples:


// fileName: The file name ( With the full path )
// content:  What is written 
func appendToFile(fileName string, content string) error {
  //  Open the file in write-only mode 
  f, err := os.OpenFile(fileName, os.O_WRONLY, 0644)
  if err != nil {
   fmt.Println("cacheFileList.yml file create failed. err: " + err.Error())
  } else {
   //  Find the offset at the end of the file 
   n, _ := f.Seek(0, os.SEEK_END)
   //  Write from the offset at the end 
   _, err = f.WriteAt([]byte(content), n)
  }  
defer f.Close()  
return err}

conclusion

This site feels that the current domestic golang documentation blog is a little bit short, I hope you usually coding what experience to share with each other, let golang more and more useful! The above is the whole content of this article, I hope it can be helpful to your study or work, if you have any questions, you can leave a message to communicate.


Related articles: