Skip to content

Instantly share code, notes, and snippets.

@GhazeyAhmed
Created May 22, 2022 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GhazeyAhmed/be70d63fd69b9ce227fdff739f958b10 to your computer and use it in GitHub Desktop.
Save GhazeyAhmed/be70d63fd69b9ce227fdff739f958b10 to your computer and use it in GitHub Desktop.
Read number from file golang
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
)
func OpenFile(fileName string) (*os.File, error){
fmt.Println("Opening", fileName)
return os.Open(fileName)
}
func CloseFile(file *os.File){
fmt.Println("Closing file")
file.Close()
}
func GetFloats(fileName string)([]float64, error){
var numbers []float64
file, err := OpenFile(fileName)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(file)
for scanner.Scan(){
number, err := strconv.ParseFloat(scanner.Text(), 64)
if err != nil {
return nil, err
}
numbers = append(numbers, number)
}
CloseFile(file)
if scanner.Err() != nil{
return nil, scanner.Err()
}
return numbers, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment