C语言中如何把一个文件读入内存?

来源:百度知道 编辑:UC知道 时间:2024/06/25 19:54:23
我只会用fgetc()一个一个字符的读取文件,现在老师要求我一次把整个文件读入内存,在内存中再一个一个字符的读取,请问该如何做?

用C语言实现将一个文件读入内存方法:

#include <stdio.h>
#include <stdlib.h>
int filelength(FILE *fp);
char *readfile(char *path);
int main(void)
{
FILE *fp;
char *string;
string=readfile("c:/c.c");
printf("读入完毕\n按任意键释放内存资源\n");
//printf("%s\n",string);
system("pause");
return 0;

}
char *readfile(char *path)
{
FILE *fp;
int length;
char *ch;
if((fp=fopen(path,"r"))==NULL)
{
printf("open file %s error.\n",path);
exit(0);
}
length=filelength(fp);
ch=(char *)malloc(length);
fread(ch,length,1,fp);
*(ch+length-1)='\0';
return ch;
}
int filelength(FILE *fp)
{
int num;
fseek(fp,0,SEEK_END);
num=ftell(fp);
fseek(fp,0,SEEK_SET);
return num;
}

先获得文件长度
int length;
ifstream