Skip to content

Instantly share code, notes, and snippets.

@jdk
Created January 31, 2021 05:28
Show Gist options
  • Save jdk/583bd06b43438cec4d9093b66c6d6b90 to your computer and use it in GitHub Desktop.
Save jdk/583bd06b43438cec4d9093b66c6d6b90 to your computer and use it in GitHub Desktop.
Take a comma delimited string and put into a buf
ssize_t csv_to_buf(const char *line, uint16_t *buf, size_t len)
{
int i = 0;
ssize_t buf_len = 0;
if (line == NULL || !(strlen(line))) {
log_err("invalid line buffer, len = %lu\n", strlen(line));
return -1;
}
if (buf == NULL || len < 100) {
log_err("buf to fill is invalid\n");
return -1;
}
memset(buf, 0, len);
/* first count comma's */
while (i < strlen(line) ) {
if (line[i++] == ',')
buf_len++;
}
log_debug("number of commas in string: %zd\n", buf_len);
if (!(buf_len)) {
log_err("worst CSV ever, not a single comma\n");
return -1;
}
len = strlen(line);
i = 0;
buf_len = 0;
/* convert string to buf */
while (i < strlen(line)) {
buf[buf_len++] = strtol(&line[i], NULL, 10);
while (line[i++] != ',' && i < strlen(line));
}
i = buf_len-1;
/* chop off all appended zeros */
while (i) {
if (buf[i--] == 0)
buf_len --;
}
return buf_len;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment