I'm trying to store every line separately in an array of strings. It doesn't work the way I've written it obviously all I'm getting when I try to print array[0] is the last line of the textfile. But when I print the variable "line" inside of the while loop I can print every single line in the text file but I can only seem to store the last line of the txt file.
Is this possible to do? Or is this a limitation of getline..?
int main()
{
FILE * fp;
char *line;
ssize_t read;
size_t bufsize = 32;
int i=0;
char **array;
array = malloc(bufsize * sizeof(char));
line = malloc(bufsize * sizeof(char));
fp = fopen("testing.txt", "r");
while ((getline(&line, &bufsize, fp)) != -1) {
printf("%s", line);
array[i] = line;
i++;
}
fclose(fp);
printf("%s", array[0]);
return 0;
}
I think your problem is with array, you are indeed dynamically allocating memory for array but not array[i].
}
This should fix it
Edit after testing the program:
should be
This does not make an array of strings:
There are plenty of resources that describe how to do this. eg. How to create a dynamic array of strings. Essentially, you need to allocate space for the array, then allocate space for each the strings, a standard way might be:
As a further note, for your
while
loop:Is sufficient. Getline will return 0 once you have finished your file. Read this.
As already has been mentioned, you need to allocate space for pointers, not chars:
Also you need to allocate space for separate lines, and copy lines to it:
A mistake in your code is that all
array[i]
points to the same string in variableline
, which is refilled bygetline()
every loop cycle.It may be useful to read manual about getline. It permits allocation of strings by itself, but don't forget to use free().