- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char* ReadFileToString(const char*,int*);
- int main(){
- const char *path = "D:/workspace/cli.php";
- int size = 0;
- char *str = ReadFileToString(path, &size);
- printf("%d\\n\\n%s\\n", size, str);
- return 0;
- }
- char* ReadFileToString(const char *path,int *size){
- if(path==NULL) return NULL;
- FILE *fp;
- fp = fopen(path, "r");
- if(fp==NULL) {
- return NULL;
- }
- int charLen = sizeof(char);
- int tSize = 0;
- fseek(fp, 0, SEEK_END);
- tSize = ftell(fp);
- rewind(fp);
- char *body = NULL;
- body = (char*)calloc(tSize+1, charLen);
- if(tSize>0){
- int index = 0;
- char c;
- while((c = fgetc(fp))!=EOF){
- *(body+index) = c;
- index++;
- }
- }
- fclose(fp);
- fp = NULL;
- *size = tSize;
- return body;
- }
- //该片段来自于http://www.codesnippet.cn/detail/0912201411196.html
来源: http://www.codesnippet.cn/detail/0912201411196.html