Search code examples
carraysdynamicrealloccalloc

File to dynamic array in c


DISCLAIMER: I'm new to C.

What is the best way to convert every line in a .txt file (can be other file types too) to a dinamic calloc() array, and the other way around?

In my file I have to following:

1 Hello
2 18
3 World
4 15
etc...

I want something like this in the array:

[0] Hello
[1] 18
[2] World
[3] 15
etc...

The code i have now:

FILE *file;
file = fopen("test.txt", "r");
int i = 0;

//make dynamic calloc array
//while line!= EOF
    //put line[i] into array
    //i++
    //realloc array, size +1

fclose(file);

Is this way of doing this a good one or is there a better one? If someone could help me a little bit with the code I would be really thankful.


Solution

  • You are close to the right solution, but here you are reallocing the dynamic array every time there is a new line, what you could do, is to allocate N byte in advance in the array and realloc each time with this size, this will avoid frequent memory movement of the array and sys call:

    FILE *file;
    file = fopen("test.txt", "r");
    int i = 0;
    
    int max = 256;
    int resize = 512;
    char **arr = malloc(max * sizeof(*arr));
    
    
    //make dynamic calloc array
    //while line!= EOF
        //put line[i] into array
        //i++
    
        if(i == max)
          realloc array, size + reisze;
    
    fclose(file);