Problem reading file from SPIFFS

Posts: 1
Joined: Sun Aug 12, 2018 8:17 pm

Problem reading file from SPIFFS

Postby zexanana » Sun Aug 12, 2018 8:50 pm


I'm having trouble reading a file from SPIFFS. I have created an image with 2 files using mkspiffs tool. Successfully flashed it to the esp32 board memory, to the point where I can see in boot the total and used space (numbers which are correct with what i specified and the size of the 2 files).
For context, the program is a http server and I was trying to serve an image to a client. I was trying to: get file size; allocate memory to load the image to RAM (file_buf); fread the file into this buffer; send via one http message.

For some reason, the function fread is not reading any data, even though the file appears to open without problems and I get the correct file size. The code and the configuration I used are below. I have tried many different approaches, with different types of files. Variable bytes_read is always = 0 and file_buf has random data, if I keep requesting the file many times, eventually it will print part of the file along with some trash but the bytes_read variable always prints 0.

Partition table
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, , 0x4000,
otadata, data, ota, , 0x2000,
phy_init, data, phy, , 0x1000,
factory, app, factory, , 1M,
storage, data, spiffs, , 0x70000,
ota_0, app, ota_0, , 1M,
ota_1, app, ota_1, , 1M,

Commands I used to flash image
./mkspiffs -c files -b 4096 -p 256 -s 0x70000 spiffs.bin --chip esp32 --port COM6 --baud 115200 write_flash -z 0x110000 spiffs.bin


Code: Select all

esp_err_t file_get_handler(httpd_req_t *req) {
    FILE* file;
    char *file_buf;
    size_t bytes_read;
    unsigned int file_size = 0;
    char cont_len[8];

    file = fopen("/spiffs/pois.txt", "r");
    if(file != NULL) {
        fseek(file, 0, SEEK_END);
        file_size = ftell(file);
        fseek(file, 0, SEEK_SET);
        sprintf(cont_len, "%d", file_size);
        ESP_LOGI("SPIFFS", "File open \"/spiffs/pois.txt\". File size: %d Bytes", file_size);

        ESP_LOGI("SPIFFS", "content-length %s", cont_len);

        file_buf = (char *)malloc(file_size);
        if (file_buf == NULL) {
          ESP_LOGE("SPIFFS", "Failed to allocate memory");
          return ESP_FAIL;
        bytes_read = fread(file_buf, sizeof(file_buf), 1, file);

        ESP_LOGI("MESSAGE","%s", file_buf);

        httpd_resp_set_type(req, "text/plain");
        httpd_resp_set_hdr(req, "Content-Length", cont_len);
        httpd_resp_set_hdr(req, "Host", "ESP32");
        ESP_ERROR_CHECK(httpd_resp_send(req, file_buf, sizeof(file_buf)));
        ESP_LOGI("SPIFFS", "Data sent: %d Bytes", bytes_read);
    } else {
        ESP_LOGE("SPIFFS", "Failed to open file for sending");
    return ESP_OK;

Am I doing something wrong?
Thanks in advance!

Who is online

Users browsing this forum: No registered users and 4 guests