[Solved] File input output in c


the correct way is:

int myreadfile(void)
{
    FILE *fp;
    int i, n;
    unsigned char a[50];
    if (!(fp=fopen("x.exe","rb"))) return(0);
    while(n=fread(a,1,sizeof(a), fp))
    {
        for (i=0; i<n; i++)
            printf("%02x ",a[i]);
        printf("\n");
    }
    fclose(fp);
    return 1;
}

Note that the buffer is of type unsigned char. That is because

a) you don’t know if the file is a complete number of ints (but it is of char, i.e. bytes) and

b) in the printf call, the char will be converted to intand would the high bit of the char be a 1, it would be sign-extended, which we don’t want.

Also, fread does not try to read a whole buffer but just any number of bytes still in the file (to a maximum of the buffer).

1

solved File input output in c