I am trying to write a basic quiz program in C. It will basically store cards and answers to them. But in the meanwhile I am trying to use the new techniques I learned like variadic functions and dynamic memory allocation.
I want the program to be able to scale as I change the constants, there should be no "magic numbers" as defined by K&R. The problem is that I cannot use variables in the format parameter of fscanf. I need to define the string length by hand. In order to get over this limitation I have attempted to write a string concatanation function, that will generate the fscanf format parameter.
e.g.
char * scanf_string = et_concat(5, "%", CARD_SIZE, "s | %", ANSWER_SIZE, "s");
The constants are defined in consts.h
#define CARD_SIZE 200
#define ANSWER_SIZE 1000
#define CONCAT_SIZE 20
The et_concat function is in etstring.h. This is where the segmentation fault happens.
#include <stdarg.h>
#include <string.h>
char * et_concat (int count, char * str, ...)
{
va_list ap;
int j;
char *concatted_string = (char *) malloc (count*CONCAT_SIZE+1);
va_start(ap, str);
for (j = 0; j < count; j++) {
strcat(concatted_string, va_arg(ap, char *));
}
va_end(ap);
return concatted_string;
}
The code I am trying to call et_concat from is in reader.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "consts.h"
#include "etstring.h"
int iterate_inputs()
{
char card[CARD_SIZE];
char answer[ANSWER_SIZE];
FILE *fp = fopen("data.txt","r");
if (fp == NULL)
{
return EXIT_FAILURE;
}
char * scanf_string = et_concat(5, "%", CARD_SIZE, "s | %", ANSWER_SIZE, "s");
printf(scanf_string);
fscanf(fp, scanf_string, card, answer);
printf("%s | %s\n", card, answer);
fclose(fp);
return EXIT_SUCCESS;
}
Thanks very much in advance.