doc.odin 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. Reader and writer for comma-separated values (`CSV`) files, per [[ RFC 4180 ; https://tools.ietf.org/html/rfc4180.html ]].
  3. Example:
  4. package main
  5. import "core:fmt"
  6. import "core:encoding/csv"
  7. import "core:os"
  8. // Requires keeping the entire CSV file in memory at once
  9. iterate_csv_from_string :: proc(filename: string) {
  10. r: csv.Reader
  11. r.trim_leading_space = true
  12. r.reuse_record = true // Without it you have to delete(record)
  13. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  14. defer csv.reader_destroy(&r)
  15. csv_data, ok := os.read_entire_file(filename)
  16. if ok {
  17. csv.reader_init_with_string(&r, string(csv_data))
  18. } else {
  19. fmt.printfln("Unable to open file: %v", filename)
  20. return
  21. }
  22. defer delete(csv_data)
  23. for r, i, err in csv.iterator_next(&r) {
  24. if err != nil { /* Do something with error */ }
  25. for f, j in r {
  26. fmt.printfln("Record %v, field %v: %q", i, j, f)
  27. }
  28. }
  29. }
  30. // Reads the CSV as it's processed (with a small buffer)
  31. iterate_csv_from_stream :: proc(filename: string) {
  32. fmt.printfln("Hellope from %v", filename)
  33. r: csv.Reader
  34. r.trim_leading_space = true
  35. r.reuse_record = true // Without it you have to delete(record)
  36. r.reuse_record_buffer = true // Without it you have to each of the fields within it
  37. defer csv.reader_destroy(&r)
  38. handle, err := os.open(filename)
  39. if err != nil {
  40. fmt.eprintfln("Error opening file: %v", filename)
  41. return
  42. }
  43. defer os.close(handle)
  44. csv.reader_init(&r, os.stream_from_handle(handle))
  45. for r, i in csv.iterator_next(&r) {
  46. for f, j in r {
  47. fmt.printfln("Record %v, field %v: %q", i, j, f)
  48. }
  49. }
  50. fmt.printfln("Error: %v", csv.iterator_last_error(r))
  51. }
  52. // Read all records at once
  53. read_csv_from_string :: proc(filename: string) {
  54. r: csv.Reader
  55. r.trim_leading_space = true
  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. }
  79. */
  80. package encoding_csv