example.odin 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //+build ignore
  2. package encoding_csv
  3. import "core:fmt"
  4. import "core:encoding/csv"
  5. import "core:os"
  6. // Requires keeping the entire CSV file in memory at once
  7. iterate_csv_from_string :: proc(filename: string) {
  8. r: csv.Reader
  9. r.trim_leading_space = true
  10. r.reuse_record = true // Without it you have to delete(record)
  11. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  12. defer csv.reader_destroy(&r)
  13. csv_data, ok := os.read_entire_file(filename)
  14. if ok {
  15. csv.reader_init_with_string(&r, string(csv_data))
  16. } else {
  17. fmt.printfln("Unable to open file: %v", filename)
  18. return
  19. }
  20. defer delete(csv_data)
  21. for r, i, err in csv.iterator_next(&r) {
  22. if err != nil { /* Do something with error */ }
  23. for f, j in r {
  24. fmt.printfln("Record %v, field %v: %q", i, j, f)
  25. }
  26. }
  27. }
  28. // Reads the CSV as it's processed (with a small buffer)
  29. iterate_csv_from_stream :: proc(filename: string) {
  30. fmt.printfln("Hellope from %v", filename)
  31. r: csv.Reader
  32. r.trim_leading_space = true
  33. r.reuse_record = true // Without it you have to delete(record)
  34. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  35. defer csv.reader_destroy(&r)
  36. handle, err := os.open(filename)
  37. if err != nil {
  38. fmt.eprintfln("Error opening file: %v", filename)
  39. return
  40. }
  41. defer os.close(handle)
  42. csv.reader_init(&r, os.stream_from_handle(handle))
  43. for r, i in csv.iterator_next(&r) {
  44. for f, j in r {
  45. fmt.printfln("Record %v, field %v: %q", i, j, f)
  46. }
  47. }
  48. fmt.printfln("Error: %v", csv.iterator_last_error(r))
  49. }
  50. // Read all records at once
  51. read_csv_from_string :: proc(filename: string) {
  52. r: csv.Reader
  53. r.trim_leading_space = true
  54. r.reuse_record = true // Without it you have to delete(record)
  55. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  56. defer csv.reader_destroy(&r)
  57. csv_data, ok := os.read_entire_file(filename)
  58. if ok {
  59. csv.reader_init_with_string(&r, string(csv_data))
  60. } else {
  61. fmt.printfln("Unable to open file: %v", filename)
  62. return
  63. }
  64. defer delete(csv_data)
  65. records, err := csv.read_all(&r)
  66. if err != nil { /* Do something with CSV parse error */ }
  67. defer {
  68. for rec in records {
  69. delete(rec)
  70. }
  71. delete(records)
  72. }
  73. for r, i in records {
  74. for f, j in r {
  75. fmt.printfln("Record %v, field %v: %q", i, j, f)
  76. }
  77. }
  78. }