Read and write struct array SPIFFS

Hello friend, How do you read and write struct array configurations in Spiffs? I will keep examples like this:

[image]

struct myText{
  byte enable =1;
  byte color=1;
  byte speed=2;
  char text[220]=" text Default ";
};
myText runText[20];

Hi @herry93 !

Please note that SPIFFS is deprecated and has been replaced by LittleFS.

Here are two generic functions for reading and writing binary files that can be used with any file system:

bool readBinaryFile(fs::FS& fs, const char* filename, uint8_t* buf, size_t size) {
    File f = fs.open(filename, "r", false);

    if (!f) {
        log_e("File %s does not exist", filename);
        return false;
    }

    if (f.size() != size) {
        log_e("Filesize mismatch for file %s!", filename);
        f.close();
        return false;
    }

    const size_t bytes_read = f.read(buf, size);
    f.close();

    if (bytes_read != size) {
        log_e("Error occurred while reading from file %s", filename);
        return false;
    }

    return true;
};

bool writeBinaryFile(fs::FS& fs, const char* filename, const uint8_t* buf, size_t size) {
    File f = fs.open(filename, "w", true);

    if (!f) {
        log_e("Could not write to file %s", filename);
        return false;
    }

    const size_t bytesWritten = f.write(buf, size);
    f.close();

    if (bytesWritten != size) {
        log_e("Error occurred while writing to file %s", filename);
        return false;
    }

    return true;
};

Example functions how to read and write the runText from various file systems:

SPIFFS

  • requires: #include <SPIFFS.h>
bool readRunTextFromSPIFFSFile(const char* filename) {
    return readBinaryFile(SPIFFS, filename, (uint8_t*)runText, sizeof(runText));
}

bool writeRunTextToSPIFFSFile(const char* filename) {
    return writeBinaryFile(SPIFFS, filename, (const uint8_t*)runText, sizeof(runText));
}

LittleFS

  • requires: #include <LittleFS.h>
bool readRunTextFromLittleFSFile(const char* filename) {
    return readBinaryFile(LittleFS, filename, (uint8_t*)runText, sizeof(runText));
}

bool writeRunTextToLittleFSFile(const char* filename) {
    return writeBinaryFile(LittleFS, filename, (const uint8_t*)runText, sizeof(runText));
}

FAT

  • requires: #include <FFat.h>
bool readRunTextFromFATFile(const char* filename) {
    return readBinaryFile(FFat, filename, (uint8_t*)runText, sizeof(runText));
}

bool writeRunTextToFATFile(const char* filename) {
    return writeBinaryFile(FFat, filename, (const uint8_t*)runText, sizeof(runText));
}

Example how you can read runText from SPIFFS

void loadRunText() {
    const char* config_filename "/runText.bin";

    if (!readRunTextFromSPIFFSFile(config_filename)) {
        log_e("Failed to read config file. Creating new...");
        if (!writeRunTextToSPIFFSFile(config_filename)) {
            log_e("Failed to write config file!");
        }
    }
}

I hope this helps you.