doc.odin 2.4 KB

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