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

我只会用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;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-15
先获得文件长度
int length;
ifstream fin(pFilename.c_str());
fin.seekg (0, ios::end);
length = fin.tellg();
fin.seekg (0, ios::beg);
再一次性申请内存
char *ch = new char[length];
读入文件
fin.read((char *)&ch ,sizeof(char)*length);
sorry刚才查了一下ifstream 是C++的本回答被提问者采纳
第2个回答  2009-07-26
fgetc()是一个一个的字符读取。fscanf()从指定的文件按格式输入数据。fprintf()按指定的格式将数据写道指定的文件。“%s”可以整个字符串进行
。fscanf(fp,"%s",& )
第3个回答  2009-07-26
要知道文件的长度,然后分配文件长度大小的内存,最后用fread读取
相似回答