代碼如下,執行完之后被分配的動態內存的指針會保存到result中。由於是動態分配內存,讀取內容不再使用之后注意用free 釋放掉,如不明白,請多搜索以下動態內存分配的資料。
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
//從文件讀取所有數據,並且保存到result中
//參數二:文件的位置
//返回值:成功返回1,失敗返回0
int read_data(char **result,char *fileName)
{
struct stat fileInfo;
FILE *filePointer;
char *fileDate;
if((fileName==NULL)||(result==NULL))
{
return 0;
}
if(!(filePointer=fopen(fileName,"rb ")))
{return 0;}
stat(fileName,&fileInfo);
fileDate=malloc(sizeof(char)*(fileInfo.st_size+1));
fread(fileDate,sizeof(char),fileInfo.st_size,filePointer);
fclose(filePointer);
fileDate[fileInfo.st_size]=0;
printf("\n%s\n",fileDate);
*result=fileDate;
return 1;
}
