I have a program that will fetch some particular lines and store it in a buffer for further operations.The code which is given below works but with some errors.I couldn't trace out the error.Can anybody help on this plz??
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define LINESIZE 256
void failif (int condition, char * message)
{
if (condition)
{
printf("%s\n", message);
exit(EXIT_FAILURE);
}
}
void read_lines (char * * lines_array, FILE * fp, int start, int end)
{
char line[LINESIZE];
int i = 0, line_counter = 1;
while(fgets(line, sizeof(line), fp) != NULL)
{
//Once line_counter matches up with start, "start recording" till end.
if((line_counter >= start) && (line_counter <= end))
{
lines_array[i++] = strdup(line);
}
line_counter++;
}
}
int main (int argc, char const *argv[])
{
FILE *fp;
int start,end,i;
char * * lines_array;
failif (argc != 4, "this program requieres three arguments");
fp = fopen(argv[1], "rb");
failif (!fp, "Could Not Open File");
// The line range I want
start = atoi(argv[2]);
end = atoi(argv[3]);
// allocate storage for the lines:
lines_array = (char **) malloc((end - start) * sizeof(char *));
failif (!lines_array, "memory allocation failed");
read_lines (lines_array, fp, start, end);
for(i = 1; i <( end - start)+1; ++i)
{
printf("\n%d.%s",i, lines_array);
}
new code: free memory used by the allocated storage
for (i = 0; i < end - start; i++)
free (lines_array);
free (lines_array);
return 0;
}