Home > Net >  C read file line by line into char**
C read file line by line into char**

Time:01-13

I want to store data from a textfile into a char**.

.txt File:
First Line
Second Line
....

Now i would like to print second line like this:

printf("%s", lines[1]);

Here's my Code so far, but what's wrong here?

char* line = malloc(1000);
char** lines = malloc(10000);
FILE *file = fopen(file_path, "r");

int i = 0;
while(fgets(line, 1000, file) != NULL)
{
    lines[i] = line;
    printf("%s", line);
    i  ;
}
free(line);

CodePudding user response:

The common way for that is to consistenly read every line into the same buffer, and store a copy of that line in the lines array:

char line[1000]
int i = 0, nlines = 10000;
char **lines = malloc(nlines * sizeof(*lines));

while (fgets(line, sizeof(line), file) != NULL) {
    if (i == nlines) {      // must alloc more lines
        nlines *= 2;
        char **tmp = realloc(lines, nlines);
        if (tmp == NULL) {
            perror("Memory allocation error in realloc");
            break;
        }
        lines = tmp;
    }
    lines[i] = strdup(line);
    if (NULL == lines[i]) {
        perror("Memory allocation error in strdup");
        break;
    }
      i;
}

Provided you have enough available memory, the above code will accept as many line as you want, or will stop if no memory can be allocated any more, but still keep whatever has been read to that point.

The main limitation is that it will split lines longer than 998 characters ( the newline and the terminating null)

  •  Tags:  
  • Related