我试图在C中编写一个函数,将一个文件读入传递给它的char数组。
SELECT * FROM USERS U
JOIN login_history L
ON U.id = L.user_id
WHERE login_at NOT BETWEEN '2017-09-25' AND '2017-10-2'
我的想法是,我会用这样的东西:
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;
}
但是每当我使用它时,程序编译时,printf都不会向控制台打印任何内容。我开始时有点理解"间接"在一个非常非常基本的程度,但有人可以向我解释为什么我的代码没有按照我期望的方式工作,以及我应该如何实现这个功能。
(这不是家庭作业,所以任何有效的解决方案或方法都是完美的)
答案 0 :(得分:2)
read_file
的最后两行应为:
fread(*bufptr, length, 1, fp);
(*bufptr)[length] = 0;
新分配的缓冲区中的指针位于*bufptr
,而不是buffer
。
但是你的程序过于复杂,你不需要传递三个参数read_file
。两个就够了,就像这样:
void read_file(char* path, char** bufptr) {
/* 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(*bufptr, length, 1, fp);
(*bufptr)[length] = 0;
}
int main(int argc, char** argv) {
char* somestring = malloc(1024); // char* somestring = NULL would be even better here
read_file("readme.txt", &somestring);
printf("In main(): %s\n", somestring);
free(somestring);
return 0;
}
为简洁起见,此处仍然没有错误检查realloc
。
答案 1 :(得分:2)
如果要在函数内部分配内存 - 则无需在外部分配。但是应该有记录的协议 - 如果失败 - 没有什么是不成功的,如果成功的话 - 调用函数负责释放缓冲区指针。
您的读取功能必须进行更多错误检查,并且还必须关闭任何分支上的文件。
以下是执行阅读的示例代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
long read_file(const char* path, char** bufptr) {
char* buffer;
int res;
size_t read;
FILE *fp;
if (path == NULL || bufptr == NULL) {
perror("Invalid parameters");
return -6;
}
/* open the file, and exit on errors */
fp = fopen(path, "rb");
if (fp == NULL) {
perror("Failed to open file");
return -1;
}
/* figure out how long the file is to allocate that memory */
res = fseek(fp, 0, SEEK_END);
if (res != 0) {
perror("Failed to seek file");
fclose(fp);
return -2;
}
long length = ftell(fp);
if (length <= 0) {
perror("Failed ftell");
fclose(fp);
return -3;
}
rewind(fp);
/* allocate memory */
buffer = malloc(length + 1);
if (buffer == NULL) {
perror("Out of memory");
fclose(fp);
return -4;
}
read = fread(buffer, 1, length, fp);
fclose(fp);
if ((long)read != length) {
perror("Failed to read whole file");
free(buffer);
return -5;
}
buffer[length] = 0;
*bufptr = buffer;
return length;
}
int main() {
char* somestring;
long res = read_file("c:/key.txt", &somestring);
if (res < 0) {
//nothing is leaked - everything opened or allocated was closed and freed by the function
exit(res);
}
printf("In main(): %s\n", somestring);
free(somestring);
return 0;
}