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
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+13.2k Golang : Convert(cast) int to int64
+14k Golang : How to determine if a year is leap year?
+24.6k Golang : GORM read from database example
+6.2k Golang : Grab news article text and use NLP to get each paragraph's sentences
+26.9k Golang : Find files by extension
+10.7k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+12.9k Golang : Convert IPv4 address to packed 32-bit binary format
+9.4k Golang : How to get ECDSA curve and parameters data?
+14.6k Golang : How to determine if user agent is a mobile device example
+12.2k Golang : Split strings into command line arguments
+12k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example