I have to read text file line by line to multidimensional array. I have this code:

char *data;
data = (char*)malloc(size_d);
while(fgets(data, size_d, fp) != NULL)
{
   printf("[%d] %s ", strlen(data), data);
}

I want to put every line to char array. Some suggestions?

Recommended Answers

All 2 Replies

Some suggestions?

You've got the right idea, just expand on it:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if (argc > 1) {
        FILE *in = fopen(argv[1], "r");

        if (in != NULL) {
            char **lines = NULL;
            char line[BUFSIZ];
            size_t i, n = 0;

            while (fgets(line, sizeof line, in) != NULL) {
                char **save = realloc(lines, ++n * sizeof *lines);

                if (save == NULL) {
                    fprintf(stderr, "Error allocating memory for line #%d\n", n);
                    break;
                }

                lines = save;
                line[strcspn(line, "\n")] = '\0';
                lines[n - 1] = malloc(strlen(line) + 1);
                strcpy(lines[n - 1], line);
            }

            fclose(in);

            for (i = 0; i < n; i++)
                printf(">%s<\n", lines[i]);

            for (i = 0; i < n; i++)
                free(lines[i]);
            free(lines);
        }
    }

    return 0;
}
commented: Very helpful code snippet +5

Love you :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.