Skip to content

Instantly share code, notes, and snippets.

@natdm
Created September 26, 2016 15:40
Show Gist options
  • Save natdm/e49f344dca4f4b72f31b12b3aa864f10 to your computer and use it in GitHub Desktop.
Save natdm/e49f344dca4f4b72f31b12b3aa864f10 to your computer and use it in GitHub Desktop.
Check if a file has a particular set of bytes in it, and replace it with other bytes.
package main
import (
"bytes"
"io/ioutil"
"log"
"os"
)
//Open a file, read the bytes, check if the bytes have a sequence of bytes, then replace those bytes with other ones
//to test, make a file called "test.txt" and write something in it that has "hello" (lower case). eg, "hello, world"
func main() {
hello := []byte("hello") //The word to compare against, as bytes
holla := []byte("holla") //The word to change to, as bytes
//Open the test file with read/write rights ( my file said, "Go says hello world")
f, err := os.OpenFile("test.txt", os.O_APPEND|os.O_RDWR, os.ModeAppend)
if err != nil {
log.Fatalln(err.Error())
}
defer f.Close() //Be nice and close the file at the end of main
bs, err := ioutil.ReadAll(f) //Use a utility to read the entire stream of bytes in from the file
if err != nil {
log.Fatalln(err.Error())
}
//compare the bytes to the hello byte slice to see if it's there. If so, the index is honest. If not, kill the app
hasWord, start := compare(bs, hello)
if !hasWord {
log.Fatalf("File does not have %s\n", string(hello))
}
for i := range holla {
bs[start+i] = holla[i] //for each byte in bs that correlates to hello, change it to the holla one.
}
_, err = f.WriteAt(bs, 0) //write the new slice of bytes to the file and check for errors. Ignore the count of bytes written.
if err != nil {
log.Fatalln(err.Error())
}
log.Println("Done")
}
//comprae compares a source slice against a compare-to slice to see if the source has a particular slice of bytes
//returns true or false, and possibly an offset/location
func compare(src, compare []byte) (bool, int) {
for i := range src {
if src[i] == compare[0] {
return bytes.Equal(src[i:i+len(compare)], compare), i
}
}
return false, 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment