c - 将文件读入函数内的数组
问题描述
我正在尝试学习 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
因为我不知道文件将有多少行。
任何解决/理解此问题的帮助将不胜感激。
解决方案
推荐阅读
- javascript - 将html表单保存到表格中?
- python - 无法创建能够满足特定条件的 xpath
- dart - btw `BehaviorSubject` 和 `Sink` 有任何关系吗?和“流控制器”?
- scala - 需要帮助理解语法
- c - C中的嵌套if语句
- javascript - 如何使用带有 commonjs 插件的汇总部分包含 Node.js 模块
- c - 如何在循环中生成随机数,然后每 1000000 个数字将其存储在一个文件中?
- assembly - IDA 反汇编为在 Visual Studio 2017 中编译的 exe 生成与 ASM 文件完全不同的代码
- c - 在 Linux 中使用声卡。理解第一个例子(为什么不 UB?)
- json - 将 JSON 错误解析为 ArrayList