-3

I have a config file that contains lots of information but at the end it contains multiple key value pairs. Actually in the form of

item=a
item=b
item=c

I am trying to find the best way of removing these key value pairs using go, does anyone have a good example.

I looked into it and i found i could read a file and output it to another but wasn't sure if i could do it to the same file.

I also notice that you can open the for for append which could serve what I need.

The process would be - remove all key value pairs as explained above

and afterwards I need to add a new list of key value pairs

For example I could append to the file like so

 f, err := os.OpenFile("myconfig.conf", os.O_APPEND|os.O_WRONLY,

This would allow me to push new items (append) to the file but I don't think this solves removing the items in the first place.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Martin
  • 501
  • 1
  • 4
  • 10
  • 2
    Does this answer your question? [How to read/write from/to file using Go?](https://stackoverflow.com/questions/1821811/how-to-read-write-from-to-file-using-go) – Kamol Hasan Feb 12 '20 at 09:15
  • 2
    Easiest would be to read the whole file into memory, make the changes you want, and dump the result to the same file (overwriting the previous one). – icza Feb 12 '20 at 09:20
  • https://play.golang.org/p/YAV_UdPVo8Y – Siva Guru Feb 12 '20 at 09:47

1 Answers1

0
    file , _ := os.OpenFile("test", os.O_RDWR| os.O_CREATE, 0777)
    buf, _ := ioutil.ReadAll(file)
    fmt.Printf("your old data:%s", string(buf))
    file.Truncate(0)
    file.Seek(0, os.SEEK_SET)
    file.Write([]byte("your new data"));
kirito
  • 39
  • 4