I'm trying to learn C, and would like to have a function that takes a filename, reads each line of the file into an array and returns that array (or a pointer to it, but I guess that in the case of arrays, it's almost always a pointer already) to main()
. But I'm having the warning below, so there must be something not right in the code:
warning: incompatible pointer to integer conversion assigning to 'char' from
'char [1024]' [-Wint-conversion]
a_line[n - 1] = line;
^ ~~~~
1 warning generated.
The code is:
#define BUFFER_MAX_LENGTH 1024
#define EXIT_FAILURE 1
char * read_lines_to_arr(char *fname, FILE **fp) {
char line[BUFFER_MAX_LENGTH];
// initialise array to store lines
// https://stackoverflow.com/questions/11198604/
// static, because otherwise array would be destroyed when function finishes
static char * a_line = NULL;
int n = 0;
*fp = fopen(fname, "r");
// Check for error....
if (*fp == NULL){
printf("error: could not open file: %s\n", fname);
exit(EXIT_FAILURE);
}
while (fgets(line, sizeof(line), *fp) != NULL) {
/*
fgets doesn't strip the terminating "\n" so we do it manually
*/
size_t len = strlen(line);
if (line[len - 1] == '\n') { // FAILS when len == 0
line[len -1] = '\0';
}
// printf("%s", line);
a_line = realloc (a_line, sizeof (char*) * ++n);
if (a_line == NULL)
exit (-1); // memory allocation failed
a_line[n - 1] = line; // <- this line is giving the warning
}
a_line = realloc(a_line, sizeof (char*) * (n + 1));
a_line[n] = 0;
return a_line;
}
I think I need to use realloc
/malloc
in this case because I don't know how many lines the file will have.
Any help to solve/understand this would be kindly appreciated.