Read binary file, save to buffer, output buffer contents

I have a big problem that needs to be resolved before I can continue my program.

I need to open the binary file, read its contents, save the contents to the buffer, allocate space on the heap using malloc, close the file and finally printf (the contents of the .bin file). I came this far (closing file not yet implemented):

void executeFile(char *path){ FILE *fp; /*filepointer*/ size_t size; /*filesize*/ unsigned int buffer []; /*buffer*/ fp = fopen(path,"rb"); /*open file*/ fseek(fp, 0, SEEK_END); size = ftell(fp); /*calc the size needed*/ fseek(fp, 0, SEEK_SET); buffer = malloc(size); /*allocalte space on heap*/ if (fp == NULL){ /*ERROR detection if file == empty*/ printf("Error: There was an Error reading the file %s \n", path); exit(1); } else if (fread(&buffer, sizeof(unsigned int), size, fp) != size){ /* if count of read bytes != calculated size of .bin file -> ERROR*/ printf("Error: There was an Error reading the file %s - %d\n", path, r); exit(1); }else{int i; for(i=0; i<size;i++){ printf("%x", buffer[i]); } } } 

I think I messed up the buffer, and I'm not sure I read the .bin file correctly, because I cannot print it with printf("%x", buffer[i])

Hope you guys can help.

Greetings from Germany :)

+4
source share
1 answer

Recommended Changes:

1) Change the buffer to char (byte), since ftell() will report the size in bytes ( char ) and malloc() also use the byte size.

 unsigned int buffer []; /*buffer*/ 

to

 unsigned char *buffer; /*buffer*/ 

2) This is normal, the size of bytes and buffer points for bytes, but may be clearly devoid

 buffer = malloc(size); /*allocate space on heap*/ 

to

 buffer = (unsigned char *) malloc(size); /*allocate space on heap*/ /* or for those who recommend no casting on malloc() */ buffer = malloc(size); /*allocate space on heap*/ 

3) change the second parameter from sizeof(unsigned int) to sizeof *buffer , which is 1.

 else if (fread(buffer, sizeof(unsigned int), size, fp) != size){ 

to

 else if (fread(buffer, sizeof *buffer, size, fp) != size){ 

4) Change "%x" to "%02x" otherwise the hexadecimal digits with the hexadecimal digit confuse the output. E. g. "1234" four bytes or two?

 printf("%x", buffer[i]); 

to

 printf("%02x", buffer[i]); 

5) Your cleaning at the end of the function may include

 fclose(fp); free(buffer); 
+7
source

Source: https://habr.com/ru/post/1482601/


All Articles