When I open and read a text file it works. However, when I open and try to read a binary file it stops at the first byte equal to 00
.
For example, I try to read a png file, with the below first line in hexdump:
00000000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR|
But, I end up with a string that includes only these:
00000000 89 50 4e 47 0d 0a 1a 0a 0a |.PNG.....|
This is my code.
int main(int argc, char *argv[]) {
int num = 5;
char *filename;
char *myfile;
FILE *fp;
filename = argv[1];
if((fp = fopen(filename,"rb")) == NULL) {
printf("error open file\n");
exit(1);
}
myfile = (char *) malloc(num*sizeof(char));
if(myfile==NULL) {
printf("error memory\n");
exit(1);
}
int i=0;
while(!feof(fp)) {
fread(myfile+i,sizeof(char),1,fp);
if(i==num) {
myfile = (char *) realloc(myfile,sizeof(char)*(num*2));
if(myfile==NULL) {
printf("error memory\n");
exit(1);
}
num = num*2;
}
i++;
}
fclose(fp);
printf("%s\n",myfile);
return(0);
}