首页 > 解决方案 > 将文件读入函数内的数组

问题描述

我正在尝试学习 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因为我不知道文件将有多少行。

任何解决/理解此问题的帮助将不胜感激。

标签: carrays

解决方案


推荐阅读