Write to and read from file

This commit is contained in:
Johannes Rothe 2022-02-07 23:04:01 +01:00
parent 5d93697506
commit b221562452
2 changed files with 32 additions and 3 deletions

View File

@ -1,6 +1,10 @@
package main
import "fmt"
import (
"fmt"
"io/ioutil"
"strings"
)
type deck []string
@ -21,3 +25,24 @@ func newDeck() deck {
}
return cards
}
func deal(d deck, handsize int) (deck, deck) {
return d[:handsize], d[handsize:]
}
func (d deck) toString(seperator string) string {
return strings.Join(d, "\n")
}
func fromString(input []byte, seperator string) deck {
return strings.Split(string(input), seperator)
}
func (d deck) save(filename string) error {
return ioutil.WriteFile(filename, []byte(d.toString("\n")), 0644)
}
func load(filename string) (deck, error) {
bytes, err := ioutil.ReadFile(filename)
return fromString(bytes, "\n"), err
}

View File

@ -1,6 +1,10 @@
package main
func main() {
cards := newDeck()
cards.print()
//cards := newDeck()
//cards.save("cards")
cards, _ := load("cards")
hand, remainingCards := deal(cards, 5)
hand.print()
remainingCards.print()
}