Reputation: 315
What i'm trying to do here, is to copy a binary file 32 bytes per 32 bytes. WHY am i trying to do that ? because i need to send this binary file on the USART of my board. I cannot send it in one shot, that's why i send it 32 bytes per 32 bytes.
First, i try to read my binary file into a buffer and write it in another file 3é bytes per 32 bytes. The problem is, when i try to execute the new binary file i made.. it doesn't execute on the board and i don't understand why
here's my code if you want to give a try ..
int sendBuff(char *buffer,int *size)
{
int i,n =0;
char c ;
FILE *file,target;
//Open file
file = fopen("Nucleo-L152RE_bis.bin", "rb");
if (!file)
{
fprintf(stderr, "Unable to open file %s", "Nucleo-L152RE_bis.hex");
return 0;
}
*size = getFileSize(file);
if (!buffer) {
fprintf(stderr, "Memory error!");
fclose(file);
return 0;
}
//Read file contents into buffer
fread(buffer,*size, 1, file);
fclose(file);
return 0;
}
void writefile(unsigned char *buffer,int size){
FILE *file;
int i;
file = fopen("salut.bin", "a");
if (!file)
{
fprintf(stderr, "Unable to open file %s", "Nucleo-L152RE.bin");
}
else
{
fwrite(buffer,sizeof(unsigned char),size,file);
fclose(file);
}
}
and the main function :
int main()
{
/* variables locales */
unsigned char bufferS[1000000];
int nId = 5, nChoice, nBytesWritten, nBytesRead;
int* pByteRead, pByteWritten;
int size;
int k = 0,k_hexa = 0;
/* demande du numéro du port COM */
/* boucle tant que l'on ne quitte pas */
do
{
/* menu */
//ecriture de l'executable dans un buffer
sendBuff(bufferS, &size);
printf("size of file: %d\n\n", size);
k = 0;
printf("SIZE : %d\n", size);
//send program
do
{
printf("Envoi de donnees...\r\n");
//WriteCOM(bufferS + k, 32, &nBytesWritten);
writefile(bufferS+k,32);
printf("%d octet(s) envoye(s) et k : %d .\r\n",
nBytesWritten, k);
k += 32;
// scanf("%d",&nChoice);
} while (k < size);
}
}
Upvotes: 0
Views: 169
Reputation: 1924
1)According to your implement, you add extra (32-size%32) redundant bytes to the new salut.bin, which result in the failure execution. The copy will be OK just like this way,
do
{
printf("Envoi de donnees...\r\n");
//WriteCOM(bufferS + k, 32, &nBytesWritten);
writefile(bufferS+k,32);
printf("%d octet(s) envoye(s) et k : %d .\r\n",
nBytesWritten, k);
k += 32;
// scanf("%d",&nChoice);
} while (k < size-32);
writefile(bufferS+k, size%32);
2)The wrong bin format or content would result in execute failure
, sometimes which is caused by missing some bytes or adding redundant bytes in the end of file by chance.
Upvotes: 1
Reputation:
Should we refer to the code which you posted as is? In that case you seem to be trigerring undefined behaviour because you try to read value of nBytesWritten
inside printf
. But nBytesWritten
does not seem to be initialized.
Upvotes: 1