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

60 lines
862 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"
2024-02-09 10:35:46 +01:00
//"strconv"
2024-02-04 09:45:14 +01:00
)
var names = []string{}
var err error
2024-02-09 10:35:46 +01:00
var guess string
2024-02-04 09:45:14 +01:00
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)
2024-02-09 10:35:46 +01:00
fmt.Scan(&guess)
2024-02-08 13:31:01 +01:00
2024-02-09 10:35:46 +01:00
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)
}
2024-02-08 13:31:01 +01:00
}
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-09 10:35:46 +01:00
os.Exit(2)
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
}