用C语言实现将一个文件读入内存中/**
* 用C语言实现将文件读入内存中
* 作者:学无止境
* QQ:339534039
* 自己学习写着的,欢迎大家交流
* 程序中有可多地方可优化
**/
#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;
}
写了好长时间才实现的,完后才发现原来是如此简单!!!