Std::fstream with ESP32

Hello,

How can I use the std::fstream that is include in the espressif framwork with an ESP32 ?
I’ve I try using a basic c++ code but nothing is working. The systems is not able to open/create the file.
And std::fstream works on the spiffs or on an sd card ?

image

The std::cout is working well but not the std::fstream, for both case (creation and reading) my file is not open so I’m not able to print on the file.
Maybe I need to put some prestuff in front of my file name ?

Thanks in advance

What is the complete code and platformio.ini? How do you mount the SD card of the internal SPIFFS partition, and with which root path? (The standard is /spiffs for SPIFFS btw).

Ok thx for the /spiffs but it didn’t work yet. So this is the code and the platforio.ini (which is void) maybe I need to add some info to get it work ? And for the SD, the CS pin is 16 (It work properly using the classic SD class of espressif)

image

First of all: Please do not post code as pictures. I have to type out of all the text myself.

The if statement in line 24 is also errornous: You’re creating the file2 variable but you’re checking file. You’ve already corrected that in your first edit.

However, the root of your problems seems that you do not call into the SPIFFS library at all to mount the SPIFFS partition in the filesystem. As per official examples and all tutorials out there, this is a prerequisite.

The same will apply if you start using a SD card. See official examples and code for mount point.

If I use your platformio.ini and code

#include <Arduino.h>
#include <SPIFFS.h>
#include <fstream>
#include <ostream>
#include <iostream>

void setup()
{
  delay(1000); //give serial monitor time to connect
  Serial.begin(115200);
  if (!SPIFFS.begin(true /*FORMAT_SPIFFS_IF_FAILED*/))
  {
    Serial.println("SPIFFS Mount Failed");
    return;
  }
  std::cout << "SPIFFS is mounted at standard /spiffs." << std::endl;

  std::ofstream file("/spiffs/Example.txt");
  if(file.is_open()) {
    file << "Hello world!" << std::endl;
    file.flush();
    file.close();
    std::cout << "OK Write" << std::endl;
  } else
    std::cout << "NOPE Write" << std::endl; 

  delay(1000);

  std::ifstream file2("/spiffs/Example.txt");
  if(file2.is_open()) {
    std::string str;
    file2 >> str; 
    std::cout << str << std::endl; 
    file2.close();
    std::cout << "OK Read" << std::endl;
  }
  else 
    std::cout << "NOPE Read" << std::endl;

}

void loop()
{
  // put your main code here, to run repeatedly:
}

it outputs

SPIFFS is mounted at standard /spiffs.
OK Write
Hello
OK Read

So the string it seems to have read back is Hello, space limited /separated input.

If I instead alter the code to use this to read the whole file content

  std::ifstream file2("/spiffs/Example.txt");
  if (file2.is_open())
  {
    std::string content((std::istreambuf_iterator<char>(file2)),
                        (std::istreambuf_iterator<char>()));
    std::cout << content << std::endl;
    file2.close();
    std::cout << "OK Read" << std::endl;
  }

I get

OK Write
Hello world!

OK Read

so, all works.

Ok thanks very much all works, I though that std will begin my devices, which of course don’t.

Yes sorry, I will do that next time.

Hello. I have a similar problem. How I open my archive on this code (now it prints “Erro ao abrir o arquivo”)?

#include <iostream>
#include <Arduino.h>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

vector<vector<float>> data; // Vetor que armazenará os dados do arquivo CSV

void setup()
{
  Serial.begin(115200);
  ifstream file("teste.txt"); // Abre o arquivo CSV para leitura
  if (file.is_open()) {
    string line;
    while (getline(file, line)) { // Lê cada linha do arquivo CSV
      vector<float> current_row; // Vetor que armazenará os dados da linha atual
      stringstream ss(line); // Objeto stringstream para separar os valores da linha
      string value;
      while (getline(ss, value, ',')) { // Separa os valores da linha pelo delimitador ","
      current_row.push_back(stof(value)); // Converte o valor para float e adiciona ao vetor da linha atual
    }
    data.push_back(current_row); // Adiciona a linha atual ao vetor de dados
  }
  }
  else{
  perror("\nErro ao abrir o arquivo");
    return;
  }

  file.close(); // Fecha o arquivo

  Serial.println("linhas da planilha:");
  for (auto row : data) {
    for (auto value : row) {
      Serial.print(value);
      Serial.print(", ");
    }
    Serial.println();
  }
  
}

void loop(){
  // Nada a ser feito no loop principal
}

int main() {
  setup();
}

You didn’t even initialize the filesystem? Like a SPIFFS.begin() or a LittleFS.begin()

1 Like

Thank you very much, @maxgerhardt. this is a great solution for me.