I\'m trying to concatenate part of a struct with hex values. I run over every byte in the loop and convert to hex, then I want to concatenate all the hex into one long strin
In do_file()
, you are copying the hex value for a single byte in a while loop. Thus, you should go to the next byte of character array buffer
with each iteration of the while loop i.e. buffer++
or strcpy(buffer[loop], msg);
Use strcat
instead of strcpy
. That should fix your problem.
For efficiency look into using a write pointer like char *p = buffer
and advance the write position with something like p += sprintf(p, "%02X", (ch & 0x00FF))
Also your if(loop == sz2) break
check is a useless duplicate of the while(loop < sz2)
check. The while loop won't execute if loop
is equal or bigger than sz2
.
Also wondering why you use fread
when you only want one character. fgetc
or getc
seems to be a better choice.
Also, no matter if you use fread
or getc
you need to check for the end of file. What if the file does not have sz2
bytes in it? Because all modern systems are multiprocess and multiuser, so someone might cut the file short after the call to ftell
. You should never assume things because even if you just checked it, it can change. Making that assumption is what causes TOCTTOU (Time of Check To Time Of Use) bugs.