Page 1 of 1

preferences.getstring with c-type char array

Posted: Fri Jan 26, 2024 2:32 pm
by Gilbert
The preferences documentation points out that the function
  1. size_t getString(const char* key, char* value, size_t len);
requires the exact length of the stored char array or else it will fail. My string has a variable length, defined by user input. Of course the char array has a fixed length, but that's not what the function call expects.
On the other hand, the storage of that c-string requires a null terminated char array, hence I assume that the function
  1. size_t putString(const char* key, const char* value);
only stores the characters up to (including ??? - the doc doesn't tell, but the value returned by the put function will tell) the null character.
Since the actual length of the c-string is variable I have to save the length of the c-string separately in order to retrieve it later on. I don't want to use the Arduino String Class, which should work without knowing the length of the saved string.
Is there a way to retrieve c-strings without knowing their actual length - or perhaps to store a c-string of fixed length by padding the array with null characters (what a waste ...)?
I can get the length of a stored byte [] but not of a stored char[]???

Re: preferences.getstring with c-type char array

Posted: Fri Jan 26, 2024 2:41 pm
by Gilbert
This thought just crossed my mind: maybe this is a (silly) work-around: store the c-string as a byte array using putBytes() ? Then I can get the number of bytes stored using getBytesLength() and then get the array with the actual c-string without knowing the length of the c-string...

Re: preferences.getstring with c-type char array

Posted: Fri Jan 26, 2024 2:44 pm
by lbernstone
That's not a silly workaround. Storing binary data is the exact purpose of that function.

Re: preferences.getstring with c-type char array

Posted: Fri Jan 26, 2024 3:00 pm
by Gilbert
Thanks for the advice. IMHO the getString() function is pretty useless for c-strings... (unless of course one only uses strings of a fixed length).
While we're at it: is there an easy way to get a dump of all keys in a namespace (c-code using Arduino IDE). I'm at a loss when it comes to python and IDF.

Re: preferences.getstring with c-type char array

Posted: Fri Jan 26, 2024 5:36 pm
by lbernstone
The "String" type was definitely intended for use with arduino or stdlib String. I tend to use blob a lot more often, particularly if I have configuration data that can be cast directly into/from a struct.
The iterator is pretty straight forward. This was copied directly out of the doco.
https://wokwi.com/projects/388006347833519105