我正在尝试学习C,并且希望有一个接受文件名的函数,将文件的每一行读入一个数组并返回该数组(或指向它的指针,但是我猜想是这样)的数组,几乎几乎已经是指向main()
的指针。但是我在下面有警告,因此代码中一定有不正确的地方:
warning: incompatible pointer to integer conversion assigning to 'char' from
'char [1024]' [-Wint-conversion]
a_line[n - 1] = line;
^ ~~~~
1 warning generated.
代码是:
#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;
}
在这种情况下,我认为我需要使用realloc
/ malloc
,因为我不知道文件会有多少行。
对于解决/理解此问题的任何帮助,将不胜感激。