Golang : Read integer from file into array
This tutorial will demonstrate how to read a file with integer values into array. Let say nums.txt
is a file with integer values of :
100
101
102
103
104
105
106
107
108
This code below will read the integer line by line and store the values into array.
package main
import (
"fmt"
"io"
"os"
)
func main() {
file, err := os.Open("nums.txt")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var perline int
var nums []int
for {
_, err := fmt.Fscanf(file, "%d\n", &perline) // give a patter to scan
if err != nil {
if err == io.EOF {
break // stop reading the file
}
fmt.Println(err)
os.Exit(1)
}
nums = append(nums, perline)
}
// print out the nums array content
fmt.Println(nums)
}
Output :
[100 101 102 103 104 105 106 107 108]
Hope that this simple tutorial can be useful to you.
See also : Golang : Convert file content into array of bytes
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.3k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+11.6k SSL : The certificate is not trusted because no issuer chain was provided
+5.4k Golang : How to deal with configuration data?
+11.8k How to tell if a binary(executable) file or web application is built with Golang?
+7.8k Golang : Load DSA public key from file example
+7k Web : How to see your website from different countries?
+11.3k Golang : Characters limiter example
+12.7k Golang : Sort and reverse sort a slice of bytes
+13.9k Golang : Convert spaces to tabs and back to spaces example
+6.6k Golang : Spell checking with ispell example
+7.4k Golang : Example of custom handler for Gorilla's Path usage.
+7.3k Golang : Check if one string(rune) is permutation of another string(rune)