0

For printing, justified and fixed length, seems like what everyone asks about and there are many examples that I have found, like...

package main

import "fmt"

func main() {
    values := []string{"Mustang", "10", "car"}
    for i := range(values) {
        fmt.Printf("%10v...\n", values[i])
    }

    for i := range(values) {
        fmt.Printf("|%-10v|\n", values[i])
    }
}

Situation

But what if I need to WRITE to a file with fixed length bytes?

For example: what if I have requirement that states, write this line to a file that must be 32 bytes, left justified and padded to the right with 0's

Question

So, how do you accomplish this when writing to a file?

JohnPatel23
  • 57
  • 2
  • 6

1 Answers1

2

There are analogous functions to fmt.PrintXX() functions, ones that start with an F, take the form of fmt.FprintXX(). These variants write the result to an io.Writer which may be an os.File as well.

So if you have the fmt.Printf() statements which you want to direct to a file, just change them to call fmt.Fprintf() instead, passing the file as the first argument:

var f *os.File = ... // Initialize / open file

fmt.Fprintf(f, "%10v...\n", values[i])

If you look into the implementation of fmt.Printf():

func Printf(format string, a ...interface{}) (n int, err error) {
    return Fprintf(os.Stdout, format, a...)
}

It does exactly this: it calls fmt.Fprintf(), passing os.Stdout as the output to write to.

For how to open a file, see How to read/write from/to file using Go?

See related question: Format a Go string without printing?

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thanks all, think that has helped my understanding and pointed me in the right direction. Knowing what questions to ask helps. Also, for anyone else reading this, I found these handy functions for padding. RightPad2Len https://github.com/DaddyOh/golang-samples/blob/master/pad.go – JohnPatel23 Oct 11 '18 at 16:29