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
+10.9k Golang : Simple client-server HMAC authentication without SSL example
+73.3k Golang : How to return HTTP status code?
+12.8k Golang : How to convert a number to words
+10.1k Golang : Concatenate (combine) buffer data example
+13.3k Golang : GUI with Qt and OpenCV to capture image from camera
+4.2k Golang : Constant and variable names in native language
+11.2k Golang : convert(cast) string to integer value
+12.7k Golang : Compress and decompress file with compress/flate example
+3.6k Adding Skype actions such as call and chat into web page examples
+7.4k Golang : Convert word to its plural form example
+8k Golang : How to extract video or image files from html source code
+21.8k Golang : Randomly pick an item from a slice/array example