char* Load_File_JSON(const char* filename) { FILE *fp; char *str ; long flength; fp = fopen(filename, "r"); if (!fp) { printf("!!FILE open ERROR \n"); return NULL; } fseek(fp,0,SEEK_END); flength = ftell(fp); fseek(fp,0,SEEK_SET); str = (char*)malloc(flength*sizeof(char)); assert(str!=NULL); fread(str,flength , 1, fp); printf("%s\n",str); fclose(fp); return str; }
char* Load_File_AtLength(const char* filename,unsigned int ExLength,unsigned int *ReturnLength) { FILE *fp; char *str ; long flength; fp = fopen(filename, "r"); if (!fp) { printf("!!FILE open ERROR n"); return NULL; } fseek(fp,0,SEEK_END); flength = ftell(fp); fseek(fp,0,SEEK_SET); if(flength>(long)ExLength) { str = (char*)malloc(ExLength*sizeof(char)); assert(str!=NULL); fread(str,ExLength , 1, fp); *ReturnLength = ExLength ; } else{ str = (char*)malloc(flength*sizeof(char)); assert(str!=NULL); fread(str,flength , 1, fp); *ReturnLength = flength ; } printf("%s\n",str); fclose(fp); return str; }
注意:大小不能超过 long 这么长。当然一般不会。