Created
May 22, 2022 15:21
-
-
Save GhazeyAhmed/be70d63fd69b9ce227fdff739f958b10 to your computer and use it in GitHub Desktop.
Read number from file golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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