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

60 lines
862 B
Go

package main
import (
"bufio"
"fmt"
"math/rand"
"os"
//"strconv"
)
var names = []string{}
var err error
var guess string
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]
randWord := getWord(filePath)
fmt.Printf("The chosen name is %v\n", randWord)
fmt.Scan(&guess)
if guess == randWord {
fmt.Printf("You win!\n")
} else {
fmt.Printf("You lose!\n")
}
}
func catchErr(err error) {
if err != nil {
fmt.Println(err)
os.Exit(2)
}
}
func getWord(path string) (word string) {
file, err := os.Open(path)
if err != nil {
fmt.Println(err)
os.Exit(2)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
names = append(names, scanner.Text())
}
randName := names[rand.Intn(len(names)-0)]
return randName
}