cancel
Showing results for 
Search instead for 
Did you mean: 

Is it possible to read from a file on windows and place into a string during build?

BobaJFET
Associate III

I'm looking for a way to have cubeIDE read from a .bin or .txt file on windows 11 and insert it's contents into a string array in my code during the build process. 

So, if we have a file called "file.bin" stored somewhere on windows. 

and inside this file we have "Text from file.bin"

In our code we have

unsigned char string[];

After build we have

unsigned char string[] = "Text from file.bin"

 

 

4 REPLIES 4
mƎALLEm
ST Employee

Hello,

Maybe by using the prebuild feature and develop a script that reads that "file.bin" and updates your .c file?

https://community.st.com/t5/stm32cubeide-mcus/stm32cubeide-how-to-add-a-custom-pre-post-scripts/td-p/213698

To give better visibility on the answered topics, please click on "Accept as Solution" on the reply which solved your issue or answered your question.
mfgkw
Senior

For this purpose I have a small (quite old) C++ program bin2c.cpp, which reads a file and generates initialization for a C array from it.

So from your sample file it would generate:

klwa4731@eso22169:~$ cat > file.bin
"Text from file.bin"
klwa4731@eso22169:~$ bin2c file.bin
klwa4731@eso22169:~$ cat file.bin.c 
        // file.bin.c
        // generated 29.09.2025 17:16:57 from file.bin
        // by /usb1/klaus/projekte/bin2c.cpp $Id: bin2c.cpp 2013 2023-12-10 06:37:28Z klaus $
        '\"',  'T',  'e',  'x',  't',  ' ',  'f',  'r',  'o',  'm',  ' ',  'f',  'i',  'l',  'e',  '.',
         'b',  'i',  'n', '\"', 0x0a,
        // (21 bytes written)

The generated file can be included in your C code like this:

...
unsigned char mystring[] =
{
#include "file.bin.c"
  '\0'
};
...

 

A bit different is a similiar program bin2esc.cpp. It converts a file to an escape sequence. With option -p it changes to a printable string.

(The forum SW here fails to display an example output because of the escape sequences.)

You can use the output with #include... again.

 

There are many programs out there like these...


@mfgkw wrote:

The generated file can be included in your C code like this:.


Or just have your C++ program generate a complete C source file, and include that in your Project.

Similar to this.

 

A complex system that works is invariably found to have evolved from a simple system that worked.
A complex system designed from scratch never works and cannot be patched up to make it work.
mfgkw
Senior

true, but I have no excel :)