golang-exercises/golangr/file-reader/main.go

43 lines
626 B
Go
Raw Normal View History

2024-02-04 09:45:14 +01:00
package main
import (
"bufio"
2024-02-04 09:45:14 +01:00
"fmt"
"math/rand"
2024-02-04 09:45:14 +01:00
"os"
)
var names = []string{}
var err error
func main() {
if len(os.Args) < 2 || len(os.Args) > 2 {
fmt.Println("Usage: ./file-reader names.txt")
os.Exit(1)
}
filePath := os.Args[1]
2024-02-08 13:31:01 +01:00
randWord := getWord(filePath)
2024-02-04 09:45:14 +01:00
2024-02-08 13:31:01 +01:00
fmt.Printf("The chosen name is %v\n", randWord)
}
func getWord(path string) (word string) {
file, err := os.Open(path)
2024-02-04 09:45:14 +01:00
if err != nil {
2024-02-08 13:31:01 +01:00
fmt.Println(err)
2024-02-04 09:45:14 +01:00
}
defer file.Close()
2024-02-04 09:45:14 +01:00
scanner := bufio.NewScanner(file)
2024-02-08 13:31:01 +01:00
for scanner.Scan() {
names = append(names, scanner.Text())
2024-02-04 09:45:14 +01:00
}
2024-02-08 13:31:01 +01:00
randName := names[rand.Intn(len(names)-0)]
return randName
2024-02-04 09:45:14 +01:00
}