0

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);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
skalion
  • 37
  • 1
  • 5
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Eugene Sh. Mar 04 '21 at 21:51
  • 9
    The problem is not the read part. The problem is in `printf("%s\n",myfile)`. Binary data is not string data. `%s` will naturally stop at the NUL character. – kaylum Mar 04 '21 at 21:52

1 Answers1

0

You're reading the entire file correctly. Instead, the problem lies here:

printf("%s\n",myfile);

printf doesn't know when your myfile string ends, and so assumes it's a cstring, which is terminated by the first null character.

You'd want to use fwrite instead:

fwrite(myfile, num, 1, stdout);

This isn't a complete working alternative, though -- from what I see in your code, num is likely to be higher unless your file's size is an exact power of two. You'd want to rewrite your program so that you know the exact size of the data you've read, and then replace num with that in fwrite.

Samuel Hunter
  • 527
  • 2
  • 11