C读取文件(如果你不知道文件内容SIZE)

void read_file(char *path) 
{ 
     FILE *fp = NULL; 
     char *buf = NULL; 
     char *ptr = NULL; 
     int file_begin = 0; 
     int file_end = 0; 
     int len = 0; 

     if(path == NULL) 
     { 
         printf("are you kidding!!\n"); 
     } 

     fp = fopen(path, "r"); 
     if(!fp) 
     { 
         printf("can not open this file or not exist!\n"); 
         return; 
     } 

     file_begin = ftell(fp); 
     fseek(fp, 0, SEEK_END); 
     file_end = ftell(fp); 

     buff = (char*)malloc(file_end - file_begin + 2); 
     if(!buff) 
     { 
         printf("can not get memory for buff!\n"); 
         fclose(fp); 
         return; 
     } 
     memset(buff, 0, file_end - file_begin + 2); 

     if(fread(buff, file_end - file_begin + 1, 1, fp) < 1) 
     { 
         printf("can not read the file!\n"); 
         free(buff); 
         return; 
     } 

     ptr = buff; 
     len = file_end - file_begin + 1; 
     while(len > 0) 
     { 
         printf("%c", *ptr); 
         ptr++; 
         len--; 
     } 
     free(buff); 
}

 

posted @ 2014-04-24 17:08  笨的BOY  阅读(348)  评论(0编辑  收藏  举报