Easy-to-use CSV parsing library for C language.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

67 lines
1.5 KiB

#include <string.h>
#include <stdlib.h>
#include "string.h"
char*
easycsv_set_charp_to_value(const char *rowstr,
unsigned int col)
{
/* Get first occurance of comma in str, the first value is ommited but not the comma */
char *pch = (char*) rowstr;
/* Repeat until desired col is found */
for (unsigned int i = 1; i < col; i++) {
pch = strpbrk(pch + 1, ",");
}
return pch;
}
char*
easycsv_insert_string_row(const char* val,
const char* rowstr,
unsigned int col,
unsigned int col_max)
{
size_t rowstrst = strlen(rowstr);
size_t st = 0;
size_t commas = 0;
char *pch = NULL;
char *newstr = NULL;
/* column is within limit */
if (1 <= col && col <= col_max) {
/* Set pch to start of value in rowstr */
pch = easycsv_set_charp_to_value(rowstr, col);
/* Calculate size of existing value */
st = strcspn(pch, ",");
newstr = malloc(rowstrst - st + strlen(val) + 1);
/* Copy char to newstr before value (pch) */
strncpy(newstr, rowstr, pch - rowstr);
strcat(newstr, val);
/* Set pch to after value */
pch = strchr(rowstr, ',');
/* Calculate length of rest of string */
st = strlen(pch);
/* Concentate rest of string including NULL char */
strcat(newstr, pch);
}
else {
commas = col - col_max;
// csv->cols = col;
newstr = malloc(rowstrst + commas + strlen(val) + 1);
strncpy(newstr, rowstr, rowstrst);
for (size_t i = 0; i < commas; i++)
strncat(newstr, ",", 1);
strcat(newstr, val); // append \0
}
return newstr;
}