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
+5.3k Golang : Display advertisement images or strings on random order
+4.7k Python : Find out the variable type and determine the type with simple test
+15k nginx: [emerg] unknown directive "ssl"
+42.9k Golang : Get hardware information such as disk, memory and CPU usage
+10.3k Android Studio : Simple input textbox and intercept key example
+7k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+5.3k Clean up Visual Studio For Mac installation failed disk full problem
+6.6k Default cipher that OpenSSL used to encrypt a PEM file
+6.6k Swift : substringWithRange() function example
+13.2k Golang : Get constant name from value
+16.2k Golang : Execute terminal command to remote machine example
+31.2k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions