/*to use exit*/ #include /*to use *print**/ #include /*to user file2char*/ #include "file2char.h" int convert_file2char(char const* path, char **buf){ /*declarations*/ FILE *fp; long lSize; /*TODO Check path for validity!*/ /*fopen() *filename *mode *return: set errno value in error case */ fp=fopen(path,"r"); if(fp){ fprintf(stdout,"file opened.\n"); /*set offset to file end*/ /*fseek() *stream *offset *origin */ fseek(fp,0L,SEEK_END); if (ferror(fp)){ printf ("Error seeking file\n"); } /*get file size*/ lSize = ftell( fp ); fprintf(stdout,"lSize: %ld.\n",lSize); /*set offset to file start*/ fseek(fp,0,SEEK_SET); if (ferror(fp)){ printf ("Error seeking file\n"); } /*allocate memory for entire content + null termination*/ *buf=(char *)malloc((lSize+1)*sizeof(char)); if(!*buf){ fclose(fp); fputs("Error allocating memory",stderr); exit(EXIT_FAILURE); } fprintf(stdout,"mem allocated.\n"); /*copy file into buffer*/ /*fread() *ptr *size *count *stream */ if( 1!=fread(*buf,lSize,1,fp)){ fclose(fp); free(*buf); fputs("Error reading entire file",stderr); exit(EXIT_FAILURE); } fprintf(stdout,"file read.\n"); /*close file*/ if(EOF==fclose(fp)){ free(*buf); exit(EXIT_FAILURE); } fprintf(stdout,"file closed.\n"); (*buf)[lSize] = '\0'; fprintf(stdout,"mem null terminated.\n"); }else{ perror(path); exit(EXIT_FAILURE); } /*done*/ return 0; }