Allocate memory space and then read
#include
#include
intfilelength( FILE*fp);
char*readfile(char*path);
intmain(void)
{
FILE*fp ;
char*string;
string=readfile("c:/c.c");
printf("Reading completed\nPress any key to release Memory resources\n");
//printf("%s\n",string);
system("pause");
return0 ;
}
char*readfile(char*path)
{
FILE*fp;
intlength;
char*ch;
if((fp=fopen(path,"r"))==NULL)
{
printf("openfile%serror.\n",path);
exit(0);
}
length=filelength(fp) ;
ch=(char*)malloc(length);
fread(ch,length,1,fp);
*(ch+length- 1)='\0';
returnch;
}
intfilelength(FILE*fp)
{
intnum;
fseek(fp,0,SEEK_END);
num=ftell(fp);
fseek(fp,0,SEEK_SET) ;
returnnum;
}
Extended information
cLinux inter-process communication ***shared memory:
#include "comm.h"
staticintcommShm(intsize,intflags)//Create shared memory
{
key_tkey=ftok(PATHNAME, PROJ_ID);
if(key<0){
perror("ftok");
return-1;
}
intshmid=shmget(key,size,flags);
if(shmid<0){
perror("shmget");
return-2;
}
returnshmid;
}
intcreateShm(intsize)
{
returncommShm(size,IPC_CREAT|IPC_EXCL);
}
intgetShm(intsize)//Get *** shared memory
{
returncommShm(size,IPC_CREAT);
}
intdestoryShm(intshmid)//Destroy shared memory
{
if(shmctl(shmid,IPC_RMID,NULL)<0){
perror("shmctl");
return-3;
}
}