csv.c 769 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #include "csv.h"
  2. int csv_find_index(char *header, const char **names, size_t names_len)
  3. {
  4. char *split = header;
  5. for (int idx = 0; split != NULL; ++idx) {
  6. char *front = (idx == 0) ? split : split + 1;
  7. for (size_t i = 0; i < names_len; ++i) {
  8. if (strncmp(front, names[i], strlen(names[i])) == 0) {
  9. return idx;
  10. }
  11. }
  12. split = strchr(front, ',');
  13. }
  14. return -1;
  15. }
  16. char* csv_get_index(char *row, size_t idx)
  17. {
  18. char *split = row;
  19. for (size_t i = 0; i < idx; ++i) {
  20. split = strchr(split + 1, ',');
  21. if (split == NULL) {
  22. return NULL;
  23. }
  24. }
  25. char *entry;
  26. char *start = (idx == 0) ? split : split + 1;
  27. char *end = strchr(start, ',');
  28. if (end != NULL) {
  29. entry = strndup(start, end - start);
  30. } else {
  31. entry = strdup(start);
  32. }
  33. return entry;
  34. }