Hello just looking to implement a function that initializes an array of char pointers in the string_split function bellow. wondering how to properly do this currently getting a segmentation fault. The segmentation fault occurs when i try to print the tokens in the main function. I may be approaching this the wrong way if so please point me in the right direction.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
uint32_t string_split(char **tokens, char *buffer,uint32_t len, char del);
uint32_t character_count(char * str, char c);
int main (int argc, char *argv[])
{
uint32_t i,len;
char * buffer = 0;
long length;
FILE * f;
char **tokens = NULL;
if (argc < 2)
{
printf("usage: %s <config_file>\n\r" , argv[0]);
return 0;
}
f = fopen(argv[1], "rb");
if (f)
{
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(length + 1);
if (buffer)
{
fread(buffer, 1, length, f);
buffer[length] = '\0';
}
fclose(f);
}
if (buffer)
{
//printf("%s", buffer);
len = string_split(tokens, buffer, strlen(buffer), '\n');
printf("len:%d\n\r", len);
for(i = 0; i < len; i++)
{
printf("%s\n\r", tokens[i]);
}
// start to process your data / extract strings here...
}
return 0;
}
uint32_t string_split(char **tokens, char *buffer,uint32_t len, char del)
{
uint32_t i, size, cnt;
char *token = NULL;
cnt = 0;
size = character_count(buffer,del);
//printf("size:%d\n\r", size);
tokens = malloc(size* sizeof(char *));
for(i=0; i < size; i++)
{
tokens[i] = NULL;
}
token = strtok(buffer, &del);
tokens[cnt] = token;
cnt++;
while( token != NULL ) {
//printf( " %s\n", token ); //printing each token
token = strtok(NULL, &del);
if (token != NULL)
{
tokens[cnt] = token;
cnt++;
}
}
return cnt;
}
uint32_t character_count(char * str, char c)
{
uint32_t i,cnt;
cnt = 0;
for(i=0; i < strlen(str); i++)
{
if (str[i] == c)
cnt++;
}
return cnt;
}