read_csv.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // read_csv.go
  2. package main
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "strconv"
  10. "strings"
  11. )
  12. type Book struct {
  13. title string
  14. price float64
  15. quantity int
  16. }
  17. func main() {
  18. bks := make([]Book, 1)
  19. file, err := os.Open("products.txt")
  20. if err != nil {
  21. log.Fatalf("Error %s opening file products.txt: ", err)
  22. }
  23. defer file.Close()
  24. reader := bufio.NewReader(file)
  25. for {
  26. // read one line from the file:
  27. line, err := reader.ReadString('\n')
  28. if err == io.EOF {
  29. break
  30. }
  31. // remove \r and \n so 2(in Windows, in Linux only \n, so 1):
  32. line = string(line[:len(line)-2])
  33. //fmt.Printf("The input was: -%s-", line)
  34. strSl := strings.Split(line, ";")
  35. book := new(Book)
  36. book.title = strSl[0]
  37. book.price, err = strconv.ParseFloat(strSl[1], 32)
  38. if err != nil {
  39. fmt.Printf("Error in file: %v", err)
  40. }
  41. //fmt.Printf("The quan was:-%s-", strSl[2])
  42. book.quantity, err = strconv.Atoi(strSl[2])
  43. if err != nil {
  44. fmt.Printf("Error in file: %v", err)
  45. }
  46. if bks[0].title == "" {
  47. bks[0] = *book
  48. } else {
  49. bks = append(bks, *book)
  50. }
  51. }
  52. fmt.Println("We have read the following books from the file: ")
  53. for _, bk := range bks {
  54. fmt.Println(bk)
  55. }
  56. }
  57. /* Output:
  58. We have read the following books from the file:
  59. {"The ABC of Go" 25.5 1500}
  60. {"Functional Programming with Go" 56 280}
  61. {"Go for It" 45.900001525878906 356}
  62. */