1

I'm trying to create some random int arrays and write it to a xyz.txt file in Golang.
How to convert ids which is an int array to byte array, as file.Write accepts []byte as a parameter. What is the correct way to achieve writing random integer arrays to a text file.

func main() {
    var id int
    var ids []int
    var count int

    f, err := os.Create("xyz.txt")
    check(err)

    defer f.Close()

    for j := 0; j < 5; j++ {
        count = rand.Intn(100)
        for i := 0; i < product_count; i++ {
            id = rand.Intn(1000)
            ids = append(product_ids, product_id)
        }
        n2, err := f.Write(ids)
        check(err)
        fmt.Printf("wrote %d bytes\n", n2)
    }
}
3
  • 4
    Well, that depends solely on the format your file should have and has nothing to do with "converting int to byte array". Probably you should fmt.Fprintf to your file. Commented Aug 29, 2016 at 8:57
  • But I am getting this error on line f.Write(ids) that argument 1 has incompatible type. I want to write the ids in a text file. If this is not the correct way. Please tell me the correct manner of doing this. Commented Aug 29, 2016 at 9:23
  • Yeah, but a byte array is essentially an array of characters (in byte representation), I think you don't want your ints interpreted as characters but instead want to write the digits that make up the numbers (those are two different things). You should probably use fmt.Fprintf as Volker suggested. Commented Aug 29, 2016 at 9:25

1 Answer 1

1

You may use fmt.Fprint, as this simplified working sample:

package main

import (
    "bufio"
    "fmt"
    "math/rand"
    "os"
)

func main() {
    f, err := os.Create("xyz.txt")
    if err != nil {
        panic(err)
    }
    defer f.Close()
    w := bufio.NewWriter(f)
    defer w.Flush()

    for j := 0; j < 5; j++ {
        count := 4 //count := rand.Intn(100)
        for i := 0; i < count; i++ {
            fmt.Fprint(w, rand.Intn(1000), " ")
        }
        fmt.Fprintln(w)
    }
}

xyz.txt output file:

81 887 847 59 
81 318 425 540 
456 300 694 511 
162 89 728 274 
211 445 237 106 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.