I am reading data from Intel hex format file after opening it in binary mode and then creating a data (unsigned char)buffer and storing all the data in that (unsigned char)buffer in hex format.
I'm facing issue when the length of the data line is even (not including ':') program is adding 1 extra 0 at the end of the data.
//Returns content of firmware file in line by line fashion
unsigned char * readline(FILE *fp, unsigned char *buffer)
{
unsigned int ch, iterator_i = 0;
size_t buff_len = 0;
buffer = malloc(buff_len + 1);
if (!buffer) return NULL; // Out of memory
while ((ch = fgetc(fp)) != '\n' && ch != EOF)
{
buff_len++;
void *tmp = realloc(buffer, buff_len + 1);
if (tmp == NULL)
{
free(buffer);
return NULL; // Out of memory
}
buffer = tmp;
buffer[iterator_i] = (char) ch;
iterator_i++;
}
buffer[iterator_i] = '\0';
// Detect end
if (ch == EOF && (iterator_i == 0 || ferror(fp)))
{
free(buffer);
return NULL;
}
return buffer;
}
int main(){
unsigned int i, len, temp;
unsigned char * str = NULL, buf[3] = {'\0'}, data[22] = {'\0'}, *ptr = NULL, fn[30] = {'\0'}, ch;
FILE *fp = NULL;
printf("Enter FileName: ");
scanf("%s", fn);
fp = fopen(fn, "rb");
while ((str = readline(fp, 0)) != NULL)
{
printf("string: %s\n", str);
if(str[0] == ':' || strlen(str) <= 44){
len = strlen(str) - 1;
temp = 0;
for(i = 1 ; i < len-1 ; i += 2){
strncpy(buf, &str[i], 2);
buf[2]='\0';
data[temp] = (unsigned char) strtoul(buf,(char ** __restrict__) &ptr, 16);
temp++;
}
if(len % 2 == 1){
buf[0] = '0';
strncpy(&buf[1], &str[i],1);
}
else{
strncpy(buf, &str[i],2);
}
buf[2]='\0';
data[temp] = (unsigned char) strtoul (buf,(char ** __restrict__) &ptr, 16);
temp += 1;
data[temp] = '\0';
for(i = 0 ; i < temp ; i++ ){
printf("%X", data[i]);
}
printf("\n");
}
else{
printf("Error in hex record; file is corrupt.");
exit(1);
}
}
return 0;
}
So, when the value of str
is ":DEAD" my output should be "DEAD" but I'm getting "DEAD0" as output.
I've tried checking my logic several times but was not able to find the fault.. Please help me.
Thanks in advance.