DG9Jww
(Dale)
1
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.
GonzaSaya
(Gonzalo Sayago)
2
Try to use.
file.Seek(0,0)
“Truncate changes the size of the file. It does not change the I/O offset”
1 Like
alex99
(Alex Athanasopoulos)
3
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)
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)
}
system
(system)
Closed
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.