Convert int to string

I use strconv package to convert int to string.Then I write this string variable to a file.Here’s my code:

        currentTotal := 1490
	    file, err := os.OpenFile("db", os.O_RDWR, 0666)
            file.Truncate(0)
        _,err = file.WriteString(strconv.Itoa(currentTotal))

But the data written in db file actually is not what I want:


Print it: \x00\x00\x00\x00\x00\x001490
What’s going on?I just want the number.

Try to use.

file.Seek(0,0)

“Truncate changes the size of the file. It does not change the I/O offset”

1 Like

When you already have all the data in memory, consider writing the whole file with one call, like this:

	currentTotal := 1490
	s := strconv.Itoa(currentTotal)
	os.WriteFile("db", []byte(s), 0666)

It works now.Thanks!

package main

import (
“fmt”
“os”
“strconv”
)

func main() {
num := 42
str := strconv.Itoa(num)
f, err := os.Create(“output.txt”)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
f.WriteString(str)
}