This is slightly more complicated that you think. Not difficult, but it does need some concepts that you may not have met yet.
So, you have the code above (which you got directly from the
getline documentation[
^] and you want to modify it.
Fortunately, the Linux version of getline will allocate the actual memory itself, so you don;t have to worry about that bit.
So, let's declare somewhere to keep the lines:
char** lines[10];
That allocates enough space for ten lines - each line is a collection of characters (or a pointer-to-character), so we need a pointer-to-pointer-to-character to hold it, and we need a collection of them)
So now, we can save the lines - but we need to do a little setup first:
int lineIndex = 0;
lets us know what line we are doing each time, so then:
while (lineIndex < 10 && (read = getline(&line, &len, file)) != -1)
{
...
line = NULL;
lineIndex++;
}
Limits the number of lines we fetch to a number that will fit in the array of lines we defined. We also have to reset the value of
line
each time, or getline will not allocate the space for us.
while (lineIndex < 10 && (read = getline(&line, &len, file)) != -1)
{
lines[lineIndex] = line;
buf1 = line;
printf("%s", buf1);
line = NULL;
lineIndex++;
}
All we need to do now, is release the memory when we are finished:
while(lineIndex > 0)
{
lineIndex--;
if (lines[lineIndex])
{
free(lines[lineIndex]);
}
}
So what we end up with is:
int main()
{
FILE *file;
char *line = NULL;
size_t len = 0;
char read;
char *buf1;
int lineIndex = 0;
char** lines[10];
file=fopen("test.txt", "r");
if (file == NULL)
{
return 1;
}
while (lineIndex < 10 && (read = getline(&line, &len, file)) != -1)
{
lines[lineIndex] = line;
buf1 = line;
printf("%s", buf1);
line = NULL;
lineIndex++;
}
while(lineIndex > 0)
{
lineIndex--;
if (lines[lineIndex])
{
free(lines[lineIndex]);
}
}
return 0;
}
Does that make sense?