基本上问题归结为:
我加载一个文件,将所有每个字符写入一个char*变量,该变量具有malloc()文件的长度.然后我返回该变量并打印它,然后我释放()该变量的内存,并尝试再次打印该打印它的变量.
我对C很新,所以我处理保存文本内容的变量的内存可能有些不对劲.
我尝试使用char [(ftell(file)]而不是malloc和char*,但是函数没有返回任何内容.这可能是因为它是一个局部变量,当函数返回时会被释放,对吧?
这是我的代码的样子:
main.c中:
#include <stdio.h>
#include <stdlib.h>
#include "data/filesystem/files.h"
int main(){
char *filebuffer = retrieve_file_content("assets/test.txt");
printf("%s", filebuffer);
free(filebuffer);
printf("%s", filebuffer);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
files.c:
#include <stdio.h>
#include <stdlib.h>
char *retrieve_file_content(char* path){
FILE *file;
file = fopen(path, "r");
if(file){
fseek(file, 0L, SEEK_END);
char *filebuffer = malloc(ftell(file));
if(filebuffer == NULL){ return NULL; }
fseek(file, 0L, SEEK_SET);
int i = 0;
int buffer = getc(file);
while(buffer != EOF){
filebuffer[i] = buffer;
buffer = getc(file);
i++;
}
fclose(file);
return filebuffer; …Run Code Online (Sandbox Code Playgroud)