I have a big problem that need's to be solved before I can continue with my program.
I have to open a binary file, read it's content, save the content into a buffer, allocate space on the heap with malloc, close the file and finally printf( the content of the .bin file). I came this far (closing file is not implemented yet):
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 am not really sure if I read the .bin file correctly because I can't print it with printf("%x", buffer[i])
Hope you guys can help
Greetings from germany :)
size
being set? You have it commented out. – Multinuclearfopen()
,malloc()
,fseek()
.. None are being checked, though you do eventually check forfp == NULL
, but only after you blindlyfseek()
on it, and the NULL check appears to be a file-empty check (which isn't correct either) rather than failure-to-open. Read the library documentation. – Mentalistsize
out per accident->fixed – Detractionunsigned char *buffer;
. (3) Fixfread()
call to passbuffer
as the first parameter (not&buffer
), andsizeof(buffer[0])
as the second. and finally (4) close your file withfclose()
and free your buffer withfree()
. Optional checking forsize == 0
before entering into the read-and-print I leave to you. – Mentalistfstat()
might be a better way to determine file size than multiplefseek()
calls... – Jovialityunsigned int buffer[size / sizeof(int)];
in the middle of the function. That brings up another point; you are reading into an array ofint
from a file sized in terms of bytes (char
, roughly); hence the compensating/ sizeof(int)
in my suggestion. – Affairs