SPIFFS write/read problem with byte array

Here is a simple code where I write to file two bytes (233 and 78). Then I want to read them back, but instead of getting 233 and 78 I get characters 2,3,3,7,8. Of course, it's not the data at all and of course I can try to use some delimiter (",") to separate bytes from each other. But!!! I'm using SPIFFs to store a firmware.bin file that is supposed to be LARGE. This is why I'm using SPIFFS in the first place. And increasing the size of the file even more by using a delimiter is a VERY bad idea.

I googled, but I couldn't find a way to write bytes to SPIFFs.

uint16_t byte1 = 233;
  uint16_t byte2 = 78;

  Serial.println("Writing to file");
  File file = SPIFFS.open("/firmware.bin", "w");

  if (!file)
  {
    Serial.println("Error opening file for writing");
    return;
  }

  file.print((uint16_t)byte1);
  file.print((uint16_t)byte2);
  file.close();
  Serial.println("Written");

  Serial.println("Reading...");
  File file2 = SPIFFS.open("/firmware.bin", "r");

  if (!file2)
  {
    Serial.println("Failed to open file for reading");
    return;
  }

  while (file2.available())
  {
    Serial.write(file2.read());
    Serial.write("|");
  }

  Serial.println("Read");
  file2.close();
Writing to file
Written
Reading...
2|3|3|7|8|Read

Writing to file
Written
Reading...
233|78|Read

#include "FS.h"
#include "SPIFFS.h"

void setup(){
  Serial.begin(115200);
  SPIFFS.begin();

uint8_t byte1 = 233;
uint8_t byte2 = 78;

  Serial.println("Writing to file");
  File file = SPIFFS.open("/firmware.bin", "w");

  if (!file)
  {
    Serial.println("Error opening file for writing");
    return;
  }

  file.write(byte1);
  file.write(byte2);
  file.close();
  Serial.println("Written");

  Serial.println("Reading...");
  File file2 = SPIFFS.open("/firmware.bin", "r");

  if (!file2)
  {
    Serial.println("Failed to open file for reading");
    return;
  }

  while (file2.available())
  {
    Serial.print(file2.read(),DEC);
    Serial.write('|');
  }

  Serial.println("Read");
  file2.close();

}
void loop() {}
1 Like

print() converts numbers into their ascii representation so 78 turns into '7' '8'

write() does not do this conversion so numbers are written as-is.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.