I have this(albeit messy) code that parses a string and fills a struct with the data. However, I get weird results.
I get this weird output:
Check email,none,computer,0,1,1|,,computer,0,1,1|,,0,0,0|
It should be what I inputted:
Check email,none,computer,0,1,1|
Code:
int main(int argc, char **argv)
{
Task *task = load_task("Check email,none,computer,0,1,1|");
printf("%s\n", task_serialize(task));
free(task);
return 0;
}
char *task_serialize(Task *task)
{
char *result = malloc(sizeof(task));
sprintf( result, "%s,%s,%s,%i,%i,%i|",
task->task,
task->project,
task->context,
task->priority,
task->done,
task->nextAction);
return result;
}
Task *load_task(char *data)
{
Task *result = malloc(sizeof(Task));
// First get the task description
char *i = strchr(data, ',');
int in = i - data;
char *task = malloc(in);
strncpy(task, data, in - 1);
result->task = task;
free(task);
// Remove the task desc.
//strncpy(data, data + in, strlen(data));
// Get the task project
i = strchr(data, ',');
in = in + i - data;
char *project = malloc(in);
strncpy(project, data, in - 1);
result->project = project;
free(project);
// Remove the task desc.
//strncpy(data, data + in, strlen(data));
// Get the context
i = strchr(data, ',');
in = in + i - data;
char *context = malloc(in);
strncpy(context, data, in - 1);
result->context = context;
free(context);
// Remove the task desc.
//strncpy(data, data + in, strlen(data));
// Get the priority
i = strchr(data, ',');
in = in + i - data;
char *priority = malloc(in);
strncpy(priority, data, in - 1);
result->priority = atoi(priority);
free(priority);
// Remove the task desc.
//strncpy(data, data + in, strlen(data));
// Get if the task is done
i = strchr(data, ',');
in = in + i - data;
char *done = malloc(in);
strncpy(done, data, in - 1);
result->done = atoi(done);
free(done);
// Remove the task desc.
//strncpy(data, data + in, strlen(data));
// Get if the task is next action
i = strchr(data, ',');
in = in + i - data;
char *nextaction = malloc(in);
strncpy(nextaction, data, in - 1);
result->nextAction = atoi(nextaction);
free(nextaction);
return result;
}
I get this weird output:
Check email,none,computer,0,1,1|,,computer,0,1,1|,,0,0,0|
It should be what I inputted:
Check email,none,computer,0,1,1|