0

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?

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by fka
2

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;
}
Votes + Comments
Very helpful code snippet
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.