Last active
March 30, 2025 11:19
-
-
Save CelliesProjects/7fab9013517583b3a0922c0f153606a1 to your computer and use it in GitHub Desktop.
Read and write a c++ struct to a file. Arduino IDE. ESP32.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* EXAMPLE READING AND WRITING A C++ STRUCT TO A FILE | |
*/ | |
#include <FS.h> | |
#include <FFat.h> | |
const char *fileName = "/somefile.txt"; | |
struct aStruct { | |
char someString[11]; | |
float someFloat; | |
}; | |
void setup() { | |
if (!FFat.begin()) { | |
log_e("FFat Mount Failed"); | |
while (1) | |
delay(100); | |
} | |
aStruct firstStruct = { "1234567890", 1.7 }; // String is 10 chars plus a terminator '\0' | |
log_i("struct size: %i", sizeof(aStruct)); | |
File file = FFat.open(fileName, FILE_WRITE); | |
const size_t bytesWritten = file.write((byte *)&firstStruct, sizeof(firstStruct)); | |
file.close(); | |
if (bytesWritten < sizeof(aStruct)) { | |
log_e("Write error"); | |
} | |
} | |
void loop() { | |
aStruct secondStruct = { "----------", 0.0 }; | |
File file = FFat.open(fileName, FILE_READ); | |
const size_t bytesRead = file.read((byte *)&secondStruct, sizeof(secondStruct)); | |
log_i("file size: %i", file.size()); | |
if (bytesRead < file.size()) { | |
log_e("Read error"); | |
} | |
file.close(); | |
log_i("Data: %s, %.2f\n", secondStruct.someString, secondStruct.someFloat); | |
while (1) | |
delay(100); | |
} |
How to write further struct contents (records) and (random) read them in this same file?
@logowe By indexing?
Yes. Your code works fine in my app - thanks!
However, I intend to have different setups saved within the same file instead of several files with 1 record/structure each.
I'm looking for a library to prevent an own effort to add this functionality. As for writing, appending would work fine for me.
Do you know such a library or did you even realise indexed/random file access with structures?
Make a struct from your structs? Do this in a separate header file that you add to all units using it.
OK, thats a good idea! I will try it. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cleaned up the code. It is now checking the amount that has been written or read.