Home > OS >  C how to put content of .txt file into 2D array
C how to put content of .txt file into 2D array

Time:11-23

Working with C, I am trying to read from a .txt file, line by line, and then put every line into an array. Every line is 200 characters long maximum, and the array can store, lets say 50 lines. If the number of lines exceed 50, I want to dynamically allocate twice as much memory, and so on until it is enough. If I put the if{...} part outside of the while loop, it seems to work, but as soon as I use it inside of the loop it does not. I would appreciate any help.

FILE *fp=fopen(file,"r");
int idx=0;
int row=50;
int col=300;
char temp[row][col];
while (fgets(temp[idx],col,fp)){
    if (idx == row) {
        char **new = malloc(2 * row * sizeof(char *));
        for (int j = 0; j < row; j  ) {
            new[j] = (char *) malloc(col * sizeof(char)   1);
        }
        for (int i = 0; i < row; i  ) {
            for (int j = 0; j < (col   1); j  ) {
                new[i][j] = temp[i][j];
            }
        }
        row = 2 * row;
        **temp = **new;
        free(new);
    }
    idx  ;
}
fclose(fp);

CodePudding user response:

You cannot change the dimensions of a local array (here temp[row][col]). Instead you need to keep a pointer to such an array. In the following code I use a temp array just to keep one line for fgets, and then copy it immediately into a dynamically allocated storage (arr is the 2d array of lines):

FILE *fp=fopen(file,"r");
int idx=0;
int row=50;
int col=300;
char temp[col];
char **arr = malloc(row*sizeof(char*));
while (fgets(temp,col,fp)){
    if (idx == row) {
        char **new = realloc(arr, 2 * row * sizeof(char *));
        if(!new) abort();
        arr = new;
        row *= 2;
    }
    arr[idx  ] = strdup(temp);
}
fclose(fp);
  • Related