I am going to read a file from command line. And I want to store the lines in array. But the problem is I dont know the number of lines. So I dont know how to store it dynamicly in array. So please help for that. (By giving little example codes)
Asked
Active
Viewed 32 times
2 Answers
0
Use two loops, in the first loop check the size of each line and add into a variable. Once it will reach end of the file you will get the total bytes requires to store the file in an array. Now use that total bytes variable to allocate memory dynamically to an array. Now start the second loop, read each line and store into that array.

Abhijit Pritam Dutta
- 5,521
- 2
- 11
- 17
0
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
int i=0;
char **A;
A = (char **)malloc(sizeof(char *)*1); //creating char array of a[0][]
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
A = (char **)realloc(A, sizeof(char **)*(i+1)); // adding one more row to array
*(A+i) = (char *)malloc(sizeof(char)*read); //adding required column
strcpy(A[i],line); // copying line to i-th raw of array
i++;
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}

yajiv
- 2,901
- 2
- 15
- 25