【发布时间】:2017-10-02 11:38:13
【问题描述】:
我正在尝试用 C 编写一个函数,将文件读入传递给它的 char 数组。
void read_file(char* path, char** bufptr, char* buffer){
/* open the file, and exit on errors */
FILE *fp = fopen(path, "r");
if(fp == NULL){
perror("Failed to open file");
exit(1);
}
/* figure out how long the file is to allocate that memory */
fseek(fp, 0, SEEK_END);
long length = ftell(fp);
rewind(fp);
/* allocate memory */
*bufptr = realloc(*bufptr, length+1);
fread(buffer, length, 1, fp);
buffer[length] = 0;
}
我的想法是我会像这样使用它:
int main(int argc, char** argv){
char* somestring = malloc(1024);
core_read_file("/some/file/path", &somestring, somestring);
printf("In main(): %s\n", somestring);
free(somestring);
return 0;
}
但是,每当我使用它时,当程序编译时,printf 不会向控制台打印任何内容。我刚开始并在非常基本的程度上理解“间接”的概念,但是有人可以向我解释为什么我的代码不能按我期望的方式工作,以及我应该如何实现这个函数。
(这不是家庭作业,因此任何可行的解决方案或方法都是完美的)
【问题讨论】:
-
我认为您不需要
read_file的buffer参数。只需在您当前正在写buffer的任何地方写*bufptr,例如fread(*bufptr, ...); (*bufptr)[length] = 0 -
您应该使用
rb模式打开文件。还有通常的“你正在覆盖realloc中的旧指针”投诉...... -
不是
realloc,你可以malloc最初的正确数量并返回吗? -
如果 realloc 将数据移动到一个新地址,那么 buffer 指向一个无效地址(不再分配的内存)。
-
您还检查了您正在调用的函数(如 malloc、realoc、fread)和您的 core_read_file 函数的返回值,而不是 void - 如果出现问题,请返回读取错误的字节数跨度>