#include #include #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; }