example.odin 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. if csv_data, ok := os.read_entire_file(filename); ok {
  14. csv.reader_init_with_string(&r, string(csv_data))
  15. defer delete(csv_data)
  16. } else {
  17. fmt.printfln("Unable to open file: %v", filename)
  18. return
  19. }
  20. for r, i, err in csv.iterator_next(&r) {
  21. if err != nil { /* Do something with error */ }
  22. for f, j in r {
  23. fmt.printfln("Record %v, field %v: %q", i, j, f)
  24. }
  25. }
  26. }
  27. // Reads the CSV as it's processed (with a small buffer)
  28. iterate_csv_from_stream :: proc(filename: string) {
  29. fmt.printfln("Hellope from %v", filename)
  30. r: csv.Reader
  31. r.trim_leading_space = true
  32. r.reuse_record = true // Without it you have to delete(record)
  33. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  34. defer csv.reader_destroy(&r)
  35. handle, errno := os.open(filename)
  36. if errno != os.ERROR_NONE {
  37. fmt.printfln("Error opening file: %v", filename)
  38. return
  39. }
  40. defer os.close(handle)
  41. csv.reader_init(&r, os.stream_from_handle(handle))
  42. for r, i in csv.iterator_next(&r) {
  43. for f, j in r {
  44. fmt.printfln("Record %v, field %v: %q", i, j, f)
  45. }
  46. }
  47. fmt.printfln("Error: %v", csv.iterator_last_error(r))
  48. }
  49. // Read all records at once
  50. read_csv_from_string :: proc(filename: string) {
  51. r: csv.Reader
  52. r.trim_leading_space = true
  53. r.reuse_record = true // Without it you have to delete(record)
  54. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  55. defer csv.reader_destroy(&r)
  56. if csv_data, ok := os.read_entire_file(filename); ok {
  57. csv.reader_init_with_string(&r, string(csv_data))
  58. defer delete(csv_data)
  59. } else {
  60. fmt.printfln("Unable to open file: %v", filename)
  61. return
  62. }
  63. records, err := csv.read_all(&r)
  64. if err != nil { /* Do something with CSV parse error */ }
  65. defer {
  66. for rec in records {
  67. delete(rec)
  68. }
  69. delete(records)
  70. }
  71. for r, i in records {
  72. for f, j in r {
  73. fmt.printfln("Record %v, field %v: %q", i, j, f)
  74. }
  75. }
  76. }