I have some data (MARC record actually) that I'm trying to create using go (version 1.9.2) and I can't figure out how to get the delimiting characters written to the output file.
The snippet below is an example of the closest that I've been able to come up with. The first item gets written with the appropriate terminator but nothing else after that.
What is the best/correct way to write these kinds of terminator characters in go?
const fieldTerminator = 0x1e
func main() {
data := []string{"item one", "item two", "item tre"}
writer, err := os.Create("x.out")
if err != nil {
log.Fatalf("Could not open file: %q
", err)
}
defer writer.Close() // per biosckon
ft := make([]byte, 2)
binary.LittleEndian.PutUint16(ft, uint16(fieldTerminator))
for _, d := range data {
// this just proves to me that the loop is working
//os.Stderr.WriteString(fmt.Sprintf("d is %q
", d))
fmt.Fprintf(os.Stderr, "d is %q
", d) // per Andy Schweig
_, err := writer.Write([]byte(d))
if err != nil {
log.Fatalf("%q
", err)
}
// This prints the correct character at the end of the first item
// and nothing after that (items 2 and 3 not printed, no errors):
_, err = writer.Write(ft)
if err != nil {
log.Fatalf("%q
", err)
}
}
}
Edit: updated code snippet to address suggestions by Andy Schweig and biosckon.