Move purely string-manipulation function to a separate file

Signed-off-by: Pradana AUMARS <paumars@courrier.dev>
This commit is contained in:
Pradana AUMARS 2021-07-17 17:49:57 +02:00
parent b0e3062d59
commit 924e47bacc
3 changed files with 102 additions and 1 deletions

View File

@ -4,5 +4,7 @@ libeasycsv_la_SOURCES = \
easycsv_error.h \
easycsv_error.c \
easycsv_p.h \
easycsv_p.c
easycsv_p.c \
easycsv_string.h \
easycsv_string.c
include_HEADERS = ../include/easycsv.h

67
src/easycsv_string.c Normal file
View File

@ -0,0 +1,67 @@
#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;
}

32
src/easycsv_string.h Normal file
View File

@ -0,0 +1,32 @@
#ifndef EASYCSV_STRING_P_H
#define EASYCSV_STRING_P_H
/**
* Returns char pointer towards the n-th occurence of ',' in a given string
* This function does not check parameters!
* This function does not produce errors!
* @param[in] string of row (string with multiple occurences of ',')
* @param[in] n-th occurence to place the char pointer
* @return char pointer towards the n-th occurence of ',' in a given string
*/
char*
easycsv_set_charp_to_value(const char*,
unsigned int);
/**
* Insert a string in a comma-separated string of sub-strings in a specified position (by comma)
* @param[in] string to be inserted
* @param[in] comma-separated string
* @param[in] specified position of string
* @param[in] total number of sub-strings BEFORE manipulation
* @return heap-allocated string
*/
char*
easycsv_insert_string_row(const char*,
const char*,
unsigned int,
unsigned int);
#endif