I need, in ANSI C, to open a file, to read all of its lines into a dynamically allocated array of strings, and to print the first four lines. The file may be any size up to 2^31-1 bytes, while each line is at most 16 characters. I have the following, but it does not seem to work:
#define BUFSIZE 1024
char **arr_lines;
char buf_file[BUFSIZE], buf_line[16];
int num_lines = 0;
// open file
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return -1;
}
// get number of lines; from http://stackoverflow.com/a/3837983
while (fgets(buf_file, BUFSIZE, fp))
if (!(strlen(buf_file) == BUFSIZE-1 && buf_file[BUFSIZE-2] != '\n'))
num_lines++;
// allocate memory
(*arr_lines) = (char*)malloc(num_lines * 16 * sizeof(char));
// read lines
rewind(fp);
num_lines = 0;
while (!feof(fp)) {
fscanf(fp, "%s", buf_line);
strcpy(arr_lines[num_lines], buf_line);
num_lines++;
}
// print first four lines
printf("%s\n%s\n%s\n%s\n", arr_lines[0], arr_lines[1], arr_lines[2], arr_lines[3]);
// finish
fclose(fp);
I am having trouble on how to define arr_lines
in order to write into this and to easily access its elements.