Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the proper way to store a text file line by line in an array in C?

I have a text file with variable length lines which I would like to store in a dynamic array using c.

The following is the dynamic array implementation:

struct array {
    char **elements;
    long size;
    long capacity;
};

void array_init(struct array *array, long capacity)
{
    array->capacity = capacity;
    array->elements = malloc(capacity * sizeof(char*));
}

void array_push_back(struct array *array, char *element)
{
    if (array->size == array->capacity) {
        array->capacity *= 2;
        array->elements = realloc(array->elements, array->capacity * sizeof(char*));
    }
    array->elements[array->size++] = element;
}

I read the file via the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct array array;
FILE *file = fopen(filename, "r");
const unsigned MAX_LENGTH = 256;
char buffer[MAX_LENGTH];

array_init(&array, 1000);

while (fgets(buffer, MAX_LENGTH, file))
{
     array_push_back(&array, buffer);
}

for (int i = 0; i < array.size; i++)
{
     printf(array.elements[i]);
}

printf prints the last element only as many times as large the array is. I guess it is because I assign buffer‘s address to array.elements[i] and only change the content of buffer.

Can someone please help with correctly reading from a file and storing it?

>Solution :

array->elements[array->size++] = element;

You are storing a pointer to buffer from main over and over again to each element. You have to copy the content of the string.

array->elements[array->size++] = strdup(element);

or:

const size_t n = strlen(element);
array->elements[array->size] = malloc(n + 1);
memcpy(array->elements[array->size], element, n + 1);
array->size++;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading