012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
|
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
)
var spaces, magiscule bool
var tabCount, tabWidth, width int
func main() {
flag.BoolVar(&spaces, "spaces", false, "Use spaces instead of tabs for indentation")
flag.IntVar(&tabCount, "tabs", 1, "Number of tabs to indent per line")
flag.IntVar(&tabWidth, "tab-width", 4, "Number of spaces per tab")
flag.IntVar(&width, "width", 120, "Number of characters per line, including indentation")
flag.BoolVar(&magiscule, "magiscule", false, "Use uppercase hex digits")
flag.Parse()
if len(flag.Args()) < 1 {
fmt.Println("Usage: binclude file...")
os.Exit(-1)
}
for _, a := range flag.Args() {
if err := binclude(a); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
}
func binclude(name string) error {
file, err := os.Open(name)
if err != nil {
return err
}
defer file.Close()
hexWidth := width - (tabCount * tabWidth)
hexCount := ((hexWidth - 5) / 6) + 1
buf := make([]byte, hexCount)
for {
n, err := file.Read(buf)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
if n == 0 {
break
}
if spaces {
fmt.Print(strings.Repeat(" ", tabCount*tabWidth))
} else {
fmt.Print(strings.Repeat("\t", tabCount))
}
for i := range n {
if magiscule {
fmt.Printf("0x%02X, ", buf[i])
} else {
fmt.Printf("0x%02x, ", buf[i])
}
}
fmt.Println()
}
return nil
}
|