{"id":133987,"date":"2023-09-20T15:53:46","date_gmt":"2023-09-20T15:53:46","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=133987"},"modified":"2023-09-21T13:05:50","modified_gmt":"2023-09-21T13:05:50","slug":"esp32-write-data-littlefs-arduino","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp32-write-data-littlefs-arduino\/","title":{"rendered":"ESP32: Write Data to a File (LittleFS) &#8211; Arduino IDE"},"content":{"rendered":"\n<p>In this guide, you&#8217;ll learn how to write and save data permanently to a file saved on the ESP32 filesystem (LittleFS). LittleFS is a lightweight filesystem created for microcontrollers that lets you access the flash memory like you would do in a standard file system on your computer, but simple and more limited.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-Write-Data-To-a-File-LittleFS.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Write Data to a File LittleFS Arduino IDE\" class=\"wp-image-134001\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-Write-Data-To-a-File-LittleFS.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-Write-Data-To-a-File-LittleFS.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-Write-Data-To-a-File-LittleFS.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-Write-Data-To-a-File-LittleFS.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgray\">We have a similar tutorial for ESP8266 boards: <a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-write-data-littlefs-arduino\/\">ESP8266 NodeMCU: Write Data to a File (LittleFS) \u2013 Arduino IDE<\/a>.<\/p>\n\n\n\n<p><strong>Table of Contents<\/strong><\/p>\n\n\n\n<p>Throughout this tutorial, we&#8217;ll cover the following topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#littlefs-introduction\" title=\"\">Introducing LittleFS<\/a><\/li>\n\n\n\n<li><a href=\"#esp32-little-fs-handle-files\" title=\"\">ESP32 with LittleFS &#8211; Handling Files and Folders<\/a><\/li>\n\n\n\n<li><a href=\"#esp32-save-variable-littlefs\" title=\"\">ESP32 with LittleFS &#8211; How to Save Variables&#8217; Values to a File<\/a><\/li>\n\n\n\n<li><a href=\"#check-if-file-exists-littlefs\" title=\"\">ESP32 with LittleFS &#8211; Check if a file already exists<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>We\u2019ll program the ESP32 board using Arduino IDE. So, make sure you have the ESP32 add-on installed. Follow the next tutorial if you haven&#8217;t already:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/installing-the-esp32-board-in-arduino-ide-windows-instructions\/\">Install the ESP32 Board in Arduino IDE<\/a><\/li>\n<\/ul>\n\n\n\n<p>Additionally, make sure you&#8217;re running the latest version of the ESP32 add-on. Go to <strong>Tools <\/strong>&gt; <strong>Board <\/strong>&gt; <strong>Boards Manager,<\/strong> search for <strong>ESP32, <\/strong>and check that you&#8217;re running the latest version.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"littlefs-introduction\">Introducing LittleFS<\/h2>\n\n\n\n<p>LittleFS is a lightweight filesystem created for microcontrollers that lets you access the flash memory like you would do in a standard file system on your computer, but it\u2019s simpler and more limited. You can read, write, close, and delete files and folders. Using a filesystem with the ESP32 boards is especially useful to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create configuration files with settings;<\/li>\n\n\n\n<li>Save data permanently;<\/li>\n\n\n\n<li>Create files to save small amounts of data instead of using a microSD card;<\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-web-server-spiffs-spi-flash-file-system\/\">Save HTML, CSS, and JavaScript files to build a web server<\/a>;<\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/display-images-esp32-esp8266-web-server\/\">Save images, figures, and icons<\/a>;<\/li>\n\n\n\n<li>And much more.<\/li>\n<\/ul>\n\n\n\n<p class=\"rntbox rntclblue\">You may also like reading: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-littlefs-arduino-ide\/\" title=\"\">ESP32: Upload Files to LittleFS using Arduino IDE<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"esp32-little-fs-handle-files\">ESP32 with LittleFS &#8211; Handling Files and Folders<\/h2>\n\n\n\n<p>Before showing you how to write data to a file on LittleFS with the ESP32, let&#8217;s take a look at an example that shows how to do practically any task that you may need when dealing with files and folders.<\/p>\n\n\n\n<p>The following code was adapted from the official <a href=\"https:\/\/github.com\/espressif\/arduino-esp32\/blob\/master\/libraries\/LittleFS\/examples\/LITTLEFS_test\/LITTLEFS_test.ino\" target=\"_blank\" rel=\"noopener\" title=\"\">example<\/a>.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/\/ Adapted from: https:\/\/github.com\/espressif\/arduino-esp32\/blob\/master\/libraries\/LittleFS\/examples\/LITTLEFS_test\/LITTLEFS_test.ino\n\/\/ Project details: https:\/\/RandomNerdTutorials.com\/esp32-write-data-littlefs-arduino\/\n\n#include &lt;Arduino.h&gt;\n#include &quot;FS.h&quot;\n#include &lt;LittleFS.h&gt;\n\n\/\/  You only need to format LittleFS the first time you run a\n\/\/  test or else use the LITTLEFS plugin to create a partition \n\/\/  https:\/\/github.com\/lorol\/arduino-esp32littlefs-plugin\n\n#define FORMAT_LITTLEFS_IF_FAILED true\n\nvoid listDir(fs::FS &amp;fs, const char * dirname, uint8_t levels){\n    Serial.printf(&quot;Listing directory: %s\\r\\n&quot;, dirname);\n\n    File root = fs.open(dirname);\n    if(!root){\n        Serial.println(&quot;- failed to open directory&quot;);\n        return;\n    }\n    if(!root.isDirectory()){\n        Serial.println(&quot; - not a directory&quot;);\n        return;\n    }\n\n    File file = root.openNextFile();\n    while(file){\n        if(file.isDirectory()){\n            Serial.print(&quot;  DIR : &quot;);\n            Serial.println(file.name());\n            if(levels){\n                listDir(fs, file.path(), levels -1);\n            }\n        } else {\n            Serial.print(&quot;  FILE: &quot;);\n            Serial.print(file.name());\n            Serial.print(&quot;\\tSIZE: &quot;);\n            Serial.println(file.size());\n        }\n        file = root.openNextFile();\n    }\n}\n\nvoid createDir(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Creating Dir: %s\\n&quot;, path);\n    if(fs.mkdir(path)){\n        Serial.println(&quot;Dir created&quot;);\n    } else {\n        Serial.println(&quot;mkdir failed&quot;);\n    }\n}\n\nvoid removeDir(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Removing Dir: %s\\n&quot;, path);\n    if(fs.rmdir(path)){\n        Serial.println(&quot;Dir removed&quot;);\n    } else {\n        Serial.println(&quot;rmdir failed&quot;);\n    }\n}\n\nvoid readFile(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Reading file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path);\n    if(!file || file.isDirectory()){\n        Serial.println(&quot;- failed to open file for reading&quot;);\n        return;\n    }\n\n    Serial.println(&quot;- read from file:&quot;);\n    while(file.available()){\n        Serial.write(file.read());\n    }\n    file.close();\n}\n\nvoid writeFile(fs::FS &amp;fs, const char * path, const char * message){\n    Serial.printf(&quot;Writing file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path, FILE_WRITE);\n    if(!file){\n        Serial.println(&quot;- failed to open file for writing&quot;);\n        return;\n    }\n    if(file.print(message)){\n        Serial.println(&quot;- file written&quot;);\n    } else {\n        Serial.println(&quot;- write failed&quot;);\n    }\n    file.close();\n}\n\nvoid appendFile(fs::FS &amp;fs, const char * path, const char * message){\n    Serial.printf(&quot;Appending to file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path, FILE_APPEND);\n    if(!file){\n        Serial.println(&quot;- failed to open file for appending&quot;);\n        return;\n    }\n    if(file.print(message)){\n        Serial.println(&quot;- message appended&quot;);\n    } else {\n        Serial.println(&quot;- append failed&quot;);\n    }\n    file.close();\n}\n\nvoid renameFile(fs::FS &amp;fs, const char * path1, const char * path2){\n    Serial.printf(&quot;Renaming file %s to %s\\r\\n&quot;, path1, path2);\n    if (fs.rename(path1, path2)) {\n        Serial.println(&quot;- file renamed&quot;);\n    } else {\n        Serial.println(&quot;- rename failed&quot;);\n    }\n}\n\nvoid deleteFile(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Deleting file: %s\\r\\n&quot;, path);\n    if(fs.remove(path)){\n        Serial.println(&quot;- file deleted&quot;);\n    } else {\n        Serial.println(&quot;- delete failed&quot;);\n    }\n}\n\nvoid testFileIO(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Testing file I\/O with %s\\r\\n&quot;, path);\n\n    static uint8_t buf[512];\n    size_t len = 0;\n    File file = fs.open(path, FILE_WRITE);\n    if(!file){\n        Serial.println(&quot;- failed to open file for writing&quot;);\n        return;\n    }\n\n    size_t i;\n    Serial.print(&quot;- writing&quot; );\n    uint32_t start = millis();\n    for(i=0; i&lt;2048; i++){\n        if ((i &amp; 0x001F) == 0x001F){\n          Serial.print(&quot;.&quot;);\n        }\n        file.write(buf, 512);\n    }\n    Serial.println(&quot;&quot;);\n    uint32_t end = millis() - start;\n    Serial.printf(&quot; - %u bytes written in %u ms\\r\\n&quot;, 2048 * 512, end);\n    file.close();\n\n    file = fs.open(path);\n    start = millis();\n    end = start;\n    i = 0;\n    if(file &amp;&amp; !file.isDirectory()){\n        len = file.size();\n        size_t flen = len;\n        start = millis();\n        Serial.print(&quot;- reading&quot; );\n        while(len){\n            size_t toRead = len;\n            if(toRead &gt; 512){\n                toRead = 512;\n            }\n            file.read(buf, toRead);\n            if ((i++ &amp; 0x001F) == 0x001F){\n              Serial.print(&quot;.&quot;);\n            }\n            len -= toRead;\n        }\n        Serial.println(&quot;&quot;);\n        end = millis() - start;\n        Serial.printf(&quot;- %u bytes read in %u ms\\r\\n&quot;, flen, end);\n        file.close();\n    } else {\n        Serial.println(&quot;- failed to open file for reading&quot;);\n    }\n}\n\nvoid setup(){\n    Serial.begin(115200);\n\n    if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){\n        Serial.println(&quot;LittleFS Mount Failed&quot;);\n        return;\n    }\n\n    createDir(LittleFS, &quot;\/mydir&quot;); \/\/ Create a mydir folder\n    writeFile(LittleFS, &quot;\/mydir\/hello1.txt&quot;, &quot;Hello1&quot;); \/\/ Create a hello1.txt file with the content &quot;Hello1&quot;\n    listDir(LittleFS, &quot;\/&quot;, 1); \/\/ List the directories up to one level beginning at the root directory\n    deleteFile(LittleFS, &quot;\/mydir\/hello1.txt&quot;); \/\/delete the previously created file\n    removeDir(LittleFS, &quot;\/mydir&quot;); \/\/delete the previously created folder\n    listDir(LittleFS, &quot;\/&quot;, 1); \/\/ list all directories to make sure they were deleted\n    \n    writeFile(LittleFS, &quot;\/hello.txt&quot;, &quot;Hello &quot;); \/\/Create and write a new file in the root directory\n    appendFile(LittleFS, &quot;\/hello.txt&quot;, &quot;World!\\r\\n&quot;); \/\/Append some text to the previous file\n    readFile(LittleFS, &quot;\/hello.txt&quot;); \/\/ Read the complete file\n    renameFile(LittleFS, &quot;\/hello.txt&quot;, &quot;\/foo.txt&quot;); \/\/Rename the previous file\n    readFile(LittleFS, &quot;\/foo.txt&quot;); \/\/Read the file with the new name\n    deleteFile(LittleFS, &quot;\/foo.txt&quot;); \/\/Delete the file\n    testFileIO(LittleFS, &quot;\/test.txt&quot;); \/\/Testin\n    deleteFile(LittleFS, &quot;\/test.txt&quot;); \/\/Delete the file\n  \n    Serial.println( &quot;Test complete&quot; ); \n}\n\nvoid loop(){\n\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_Testing_LittleFS.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>This code covers the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#listDir\" title=\"\">List a directory;<\/a><\/li>\n\n\n\n<li><a href=\"#createDir\" title=\"\">Create a directory;<\/a><\/li>\n\n\n\n<li><a href=\"#removeDir\" title=\"\">Remove a directory;<\/a><\/li>\n\n\n\n<li><a href=\"#readFile\" title=\"\">Read a file&#8217;s content;<\/a><\/li>\n\n\n\n<li><a href=\"#writeFile\" title=\"\">Write content to a file;<\/a><\/li>\n\n\n\n<li><a href=\"#appendFile\" title=\"\">Append content to a file;<\/a><\/li>\n\n\n\n<li><a href=\"#renameFile\" title=\"\">Rename a file;<\/a><\/li>\n\n\n\n<li><a href=\"#deleteFile\" title=\"\">Delete a file;<\/a><\/li>\n\n\n\n<li><a href=\"#testing-llittlefs\" title=\"\">Initialize the LittleFS filesystem.<\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>First, you need to include the following libraries: <span class=\"rnthl rntliteral\">FS.h<\/span> to handle files, and <span class=\"rnthl rntliteral\">LittleFS.h<\/span> to create and access the filesystem.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include \"FS.h\"\n#include &lt;LittleFS.h&gt;<\/code><\/pre>\n\n\n\n<p>The first time you use LittleFS on the ESP32, you need to format it so that it creates a partition dedicated to that filesystem. To do that, we have the following boolean variable to control whether we want to format the filesystem or not.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define FORMAT_LITTLEFS_IF_FAILED true<\/code><\/pre>\n\n\n\n<p>The example provides several functions to handle files on the LittleFS filesystem. Let&#8217;s take a look at them.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"listDir\">List a directory<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">listDir()<\/span> function lists the directories on the filesystem. This function accepts as arguments the filesystem (<span class=\"rnthl rntliteral\">LittleFs<\/span>), the main directory&#8217;s name, and the levels to go into the directory.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void listDir(fs::FS &amp;fs, const char * dirname, uint8_t levels){\n    Serial.printf(\"Listing directory: %s\\r\\n\", dirname);\n\n    File root = fs.open(dirname);\n    if(!root){\n        Serial.println(\"- failed to open directory\");\n        return;\n    }\n    if(!root.isDirectory()){\n        Serial.println(\" - not a directory\");\n        return;\n    }\n\n    File file = root.openNextFile();\n    while(file){\n        if(file.isDirectory()){\n            Serial.print(\"  DIR : \");\n            Serial.println(file.name());\n            if(levels){\n                listDir(fs, file.path(), levels -1);\n            }\n        } else {\n            Serial.print(\"  FILE: \");\n            Serial.print(file.name());\n            Serial.print(\"\\tSIZE: \");\n            Serial.println(file.size());\n        }\n        file = root.openNextFile();\n    }\n}<\/code><\/pre>\n\n\n\n<p>Here&#8217;s an example of how to call this function. The <span class=\"rnthl rntliteral\">\/<\/span> corresponds to the root directory. The following command will list all the directories up to one level beginning at the root directory.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>listDir(LittleFS, \"\/\", 1); \/\/ List the directories up to one level beginning at the root directory<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"createDir\">Create a Directory<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">createDir()<\/span> function creates a new directory. Pass as an argument the <span class=\"rnthl rntliteral\">LittleFS<\/span> filesystem and the directory name path.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void createDir(fs::FS &amp;fs, const char * path){\n  Serial.printf(\"Creating Dir: %s\\n\", path);\n  if(fs.mkdir(path)){\n    Serial.println(\"Dir created\");\n  } else {\n    Serial.println(\"mkdir failed\");\n  }\n}<\/code><\/pre>\n\n\n\n<p>For example, the following command creates a new directory (folder) on the root called <span class=\"rnthl rntliteral\">mydir<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>createDir(LittleFS, \"\/mydir\"); \/\/ Create a mydir folder<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"removeDir\">Remove a Directory<\/h4>\n\n\n\n<p>To remove a directory from the filesystemca, use the <span class=\"rnthl rntliteral\">removeDir()<\/span> function and pass as an argument the <span class=\"rnthl rntliteral\">LittleFS<\/span> filesystem and the directory name path.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void removeDir(fs::FS &amp;fs, const char * path){\n  Serial.printf(\"Removing Dir: %s\\n\", path);\n  if(fs.rmdir(path)){\n    Serial.println(\"Dir removed\");\n  } else {\n    Serial.println(\"rmdir failed\");\n  }\n}<\/code><\/pre>\n\n\n\n<p>Here is an example that deletes the <em>mydir <\/em>folder.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>removeDir(LittleFS, \"\/mydir\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"readFile\">Read File Content<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">readFile()<\/span> function reads the content of a file and prints the content in the Serial Monitor. As with previous functions, pass as an argument the <span class=\"rnthl rntliteral\">LittleFs<\/span> filesystem and the file path.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void readFile(fs::FS &amp;fs, const char * path){\n  Serial.printf(\"Reading file: %s\\r\\n\", path);\n\n  File file = fs.open(path);\n  if(!file || file.isDirectory()){\n    Serial.println(\"- failed to open file for reading\");\n    return;\n  }\n\n  Serial.println(\"- read from file:\");\n  while(file.available()){\n    Serial.write(file.read());\n  }\n  file.close();\n}<\/code><\/pre>\n\n\n\n<p>For example, the following line reads the content of the <span class=\"rnthl rntliteral\">hello.txt<\/span> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>readFile(LittleFS, \"\/hello.txt\"); \/\/ Read the complete file<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"writeFile\">Write Content to a File<\/h4>\n\n\n\n<p>To write content to a file, you can use the <span class=\"rnthl rntliteral\">writeFile()<\/span> function. Pass as an argument, the <span class=\"rnthl rntliteral\">LittleFS<\/span> filesystem, the file path, and the message (as a const char variable). <\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void writeFile(fs::FS &amp;fs, const char * path, const char * message){\n  Serial.printf(\"Writing file: %s\\r\\n\", path);\n\n  File file = fs.open(path, FILE_WRITE);\n  if(!file){\n    Serial.println(\"- failed to open file for writing\");\n    return;\n  }\n  if(file.print(message)){\n    Serial.println(\"- file written\");\n  } else {\n    Serial.println(\"- write failed\");\n  }\n  file.close();\n}<\/code><\/pre>\n\n\n\n<p>The following line writes <span class=\"rnthl rntliteral\">Hello <\/span> in the <span class=\"rnthl rntliteral\">hello.txt<\/span> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>writeFile(LittleFS, \"\/hello.txt\", \"Hello \");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"appendFile\">Append Content to a File<\/h4>\n\n\n\n<p>Similarly, you can append content to a file (without overwriting previous content) using the <span class=\"rnthl rntliteral\">appendFile()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void appendFile(fs::FS &amp;fs, const char * path, const char * message){\n  Serial.printf(\"Appending to file: %s\\r\\n\", path);\n\n  File file = fs.open(path, FILE_APPEND);\n  if(!file){\n    Serial.println(\"- failed to open file for appending\");\n    return;\n  }\n  if(file.print(message)){\n    Serial.println(\"- message appended\");\n  } else {\n    Serial.println(\"- append failed\");\n  }\n  file.close();\n}<\/code><\/pre>\n\n\n\n<p>The following line appends the message <span class=\"rnthl rntliteral\">World!\\r\\n<\/span> in the <span class=\"rnthl rntliteral\">hello.txt<\/span> file. The <span class=\"rnthl rntliteral\">\\r\\n<\/span> means that the next time you write something to the file, it will be written in a new line.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>appendFile(LittleFS, \"\/hello.txt\", \"World!\\r\\n\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"renameFile\">Rename a File<\/h4>\n\n\n\n<p>You can rename a file using the <span class=\"rnthl rntliteral\">renameFile()<\/span> function. Pass as arguments the <span class=\"rnthl rntliteral\">LittleFS<\/span> filesystem, the original filename, and the new filename.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void renameFile(fs::FS &amp;fs, const char * path1, const char * path2){\n  Serial.printf(\"Renaming file %s to %s\\r\\n\", path1, path2);\n  if (fs.rename(path1, path2)) {\n    Serial.println(\"- file renamed\");\n  } else {\n    Serial.println(\"- rename failed\");\n  }\n}<\/code><\/pre>\n\n\n\n<p>The following line renames the <span class=\"rnthl rntliteral\">hello.txt<\/span> file to <span class=\"rnthl rntliteral\">foo.txt<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>renameFile(LittleFS, \"\/hello.txt\", \"\/foo.txt\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"deleteFile\">Delete a File<\/h4>\n\n\n\n<p>Use the <span class=\"rnthl rntliteral\">deleteFile()<\/span> function to delete a file. Pass as an argument the <span class=\"rnthl rntliteral\">LittleFS<\/span> filesystem and the file path of the file you want to delete.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void deleteFile(fs::FS &amp;fs, const char * path){\n  Serial.printf(\"Deleting file: %s\\r\\n\", path);\n  if(fs.remove(path)){\n    Serial.println(\"- file deleted\");\n  } else {\n    Serial.println(\"- delete failed\");\n  }\n}<\/code><\/pre>\n\n\n\n<p>The following line deletes the <span class=\"rnthl rntliteral\">foo.txt<\/span> file from the filesystem.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>deleteFile(LittleFS, \"\/foo.txt\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"testFile\">Test a File<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">testFileIO()<\/span> function shows how long it takes to read the content of a file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void testFileIO(fs::FS &amp;fs, const char * path){\n  Serial.printf(\"Testing file I\/O with %s\\r\\n\", path);\n\n  static uint8_t buf&#091;512];\n  size_t len = 0;\n  File file = fs.open(path, FILE_WRITE);\n  if(!file){\n    Serial.println(\"- failed to open file for writing\");\n    return;\n  }\n\n  size_t i;\n  Serial.print(\"- writing\" );\n  uint32_t start = millis();\n  for(i=0; i&lt;2048; i++){\n    if ((i &amp; 0x001F) == 0x001F){\n      Serial.print(\".\");\n     }\n    file.write(buf, 512);\n  }\n  Serial.println(\"\");\n  uint32_t end = millis() - start;\n  Serial.printf(\" - %u bytes written in %u ms\\r\\n\", 2048 * 512, end);\n  file.close();\n\n  file = fs.open(path);\n  start = millis();\n  end = start;\n  i = 0;\n  if(file &amp;&amp; !file.isDirectory()){\n    len = file.size();\n    size_t flen = len;\n    start = millis();\n    Serial.print(\"- reading\" );\n    while(len){\n      size_t toRead = len;\n      if(toRead &gt; 512){\n        toRead = 512;\n       }\n       file.read(buf, toRead);\n       if ((i++ &amp; 0x001F) == 0x001F){\n         Serial.print(\".\");\n       }\n       len -= toRead;\n      }\n    Serial.println(\"\");\n    end = millis() - start;\n    Serial.printf(\"- %u bytes read in %u ms\\r\\n\", flen, end);\n    file.close();\n  } else {\n    Serial.println(\"- failed to open file for reading\");\n  }\n}<\/code><\/pre>\n\n\n\n<p>The following function tests the <span class=\"rnthl rntliteral\">test.txt<\/span> file.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>testFileIO(LittleFS, \"\/test.txt\"); <\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"init-littlefs\">Initialize the Filesystem<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, the following lines initialize the LittleFS filesystem.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){\n  Serial.println(\"LittleFS Mount Failed\");\n  return;\n}<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">LittleFS.begin()<\/span> function returns <span class=\"rnthl rntliteral\">true<\/span> if the filesystem is initialized successfully or <span class=\"rnthl rntliteral\">false<\/span> if it isn&#8217;t. <\/p>\n\n\n\n<p>You can pass <span class=\"rnthl rntliteral\">true<\/span> or <span class=\"rnthl rntliteral\">false<\/span> as an argument to the <span class=\"rnthl rntliteral\">begin()<\/span> method. If you pass <span class=\"rnthl rntliteral\">true<\/span> it will format the LittleFS filesystem if the initialization fails. Because this is the first test we&#8217;re running, we set the <span class=\"rnthl rntliteral\">FORMAT_LITTLEFS_IF_FAILED<\/span> variable to <span class=\"rnthl rntliteral\">true<\/span>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"testing-llittlefs\">Testing the Filesystem<\/h4>\n\n\n\n<p>The following lines call all the functions we&#8217;ve seen previously.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>createDir(LittleFS, \"\/mydir\"); \/\/ Create a mydir folder\nwriteFile(LittleFS, \"\/mydir\/hello1.txt\", \"Hello1\"); \/\/ Create a hello1.txt file with the content \"Hello1\"\nlistDir(LittleFS, \"\/\", 1); \/\/ List the directories up to one level beginning at the root directory\ndeleteFile(LittleFS, \"\/mydir\/hello1.txt\"); \/\/delete the previously created file\nremoveDir(LittleFS, \"\/mydir\"); \/\/delete the previously created folder\nlistDir(LittleFS, \"\/\", 1); \/\/ list all directories to make sure they were deleted\n    \nwriteFile(LittleFS, \"\/hello.txt\", \"Hello \"); \/\/Create and write a new file in the root directory\nappendFile(LittleFS, \"\/hello.txt\", \"World!\\r\\n\"); \/\/Append some text to the previous file\nreadFile(LittleFS, \"\/hello.txt\"); \/\/ Read the complete file\nrenameFile(LittleFS, \"\/hello.txt\", \"\/foo.txt\"); \/\/Rename the previous file\nreadFile(LittleFS, \"\/foo.txt\"); \/\/Read the file with the new name\ndeleteFile(LittleFS, \"\/foo.txt\"); \/\/Delete the file\ntestFileIO(LittleFS, \"\/test.txt\"); \/\/Testin\ndeleteFile(LittleFS, \"\/test.txt\"); \/\/Delete the file<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Demonstration<\/h3>\n\n\n\n<p>Upload the previous sketch to your ESP32 board. After that, open the Serial Monitor and press the ESP32 on-board RST button. If the initialization succeeds, you&#8217;ll get similar messages on the Serial Monitor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"601\" height=\"791\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/testing-Little-FS-Serial-Monitor.png?resize=601%2C791&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Testing LittleFS Examples\" class=\"wp-image-133989\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/testing-Little-FS-Serial-Monitor.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/testing-Little-FS-Serial-Monitor.png?resize=228%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 228w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"esp32-save-variable-littlefs\">ESP32 with LittleFS &#8211; How to Save Variables&#8217; Values to a File<\/h2>\n\n\n\n<p>The previous example illustrated almost all the operations you might need to do when dealing with files and folders on the filesystem. In this section, we&#8217;ll take a look at a more simple and specific example: how to save the content of a variable to the filesystem.<\/p>\n\n\n\n<p>Let&#8217;s take a look at the following code.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/\/ Project details: https:\/\/RandomNerdTutorials.com\/esp32-write-data-littlefs-arduino\/\n\n#include &lt;Arduino.h&gt;\n#include &quot;FS.h&quot;\n#include &lt;LittleFS.h&gt;\n\n#define FORMAT_LITTLEFS_IF_FAILED true\n\nint mydata;\n\nvoid writeFile(fs::FS &amp;fs, const char * path, const char * message){\n    Serial.printf(&quot;Writing file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path, FILE_WRITE);\n    if(!file){\n        Serial.println(&quot;- failed to open file for writing&quot;);\n        return;\n    }\n    if(file.print(message)){\n        Serial.println(&quot;- file written&quot;);\n    } else {\n        Serial.println(&quot;- write failed&quot;);\n    }\n    file.close();\n}\n\nvoid appendFile(fs::FS &amp;fs, const char * path, const char * message){\n    Serial.printf(&quot;Appending to file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path, FILE_APPEND);\n    if(!file){\n        Serial.println(&quot;- failed to open file for appending&quot;);\n        return;\n    }\n    if(file.print(message)){\n        Serial.println(&quot;- message appended&quot;);\n    } else {\n        Serial.println(&quot;- append failed&quot;);\n    }\n    file.close();\n}\n\nvoid readFile(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Reading file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path);\n    if(!file || file.isDirectory()){\n        Serial.println(&quot;- failed to open file for reading&quot;);\n        return;\n    }\n\n    Serial.println(&quot;- read from file:&quot;);\n    while(file.available()){\n        Serial.write(file.read());\n    }\n    file.close();\n}\n\n\nvoid setup() {\n  Serial.begin(115200);\n  if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){\n      Serial.println(&quot;LittleFS Mount Failed&quot;);\n      return;\n   }\n   else{\n       Serial.println(&quot;Little FS Mounted Successfully&quot;);\n   }\n   writeFile(LittleFS, &quot;\/data.txt&quot;, &quot;MY ESP32 DATA \\r\\n&quot;);\n}\n\nvoid loop() {\n  mydata = random (0, 1000);\n  appendFile(LittleFS, &quot;\/data.txt&quot;, (String(mydata)+ &quot;\\r\\n&quot;).c_str()); \/\/Append data to the file\n  readFile(LittleFS, &quot;\/data.txt&quot;); \/\/ Read the contents of the file\n  delay(30000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_Write_File_LittleFS.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>For this example, we&#8217;ll continuously save the value of a variable to the filesystem. As an example, we&#8217;ll save a random number, but this can be easily adjusted to save sensor readings, for example.<\/p>\n\n\n\n<p>We start by creating a variable that will hold the random number called <span class=\"rnthl rntliteral\">mydata<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>int mydata;<\/code><\/pre>\n\n\n\n<p>For this particular example, we just need to use the <span class=\"rnthl rntliteral\">writeFile()<\/span>, <span class=\"rnthl rntliteral\">appendFile()<\/span>, and <span class=\"rnthl rntliteral\">readFile()<\/span> functions. So, we have those functions defined before the <span class=\"rnthl rntliteral\">setup()<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void writeFile(fs::FS &amp;fs, const char * path, const char * message){\n  Serial.printf(\"Writing file: %s\\r\\n\", path);\n\n  File file = fs.open(path, FILE_WRITE);\n  if(!file){\n    Serial.println(\"- failed to open file for writing\");\n    return;\n  }\n  if(file.print(message)){\n    Serial.println(\"- file written\");\n  } else {\n    Serial.println(\"- write failed\");\n  }\n  file.close();\n}\n\nvoid appendFile(fs::FS &amp;fs, const char * path, const char * message){\n  Serial.printf(\"Appending to file: %s\\r\\n\", path);\n\n  File file = fs.open(path, FILE_APPEND);\n  if(!file){\n    Serial.println(\"- failed to open file for appending\");\n    return;\n  }\n  if(file.print(message)){\n    Serial.println(\"- message appended\");\n  } else {\n    Serial.println(\"- append failed\");\n  }\n  file.close();\n}\n\nvoid readFile(fs::FS &amp;fs, const char * path){\n  Serial.printf(\"Reading file: %s\\r\\n\", path);\n\n  File file = fs.open(path);\n  if(!file || file.isDirectory()){\n    Serial.println(\"- failed to open file for reading\");\n    return;\n  }\n\n Serial.println(\"- read from file:\");\n while(file.available()){\n   Serial.write(file.read());\n  }\n  file.close();\n}<\/code><\/pre>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, we initialize the Serial Monitor for debugging purposes.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);<\/code><\/pre>\n\n\n\n<p>And we initialize the LittleFS filesystem:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){\n  Serial.println(\"LittleFS Mount Failed\");\n  return;\n}\nelse{\n  Serial.println(\"Little FS Mounted Successfully\");\n}<\/code><\/pre>\n\n\n\n<p>Then, we create a file called <span class=\"rnthl rntliteral\">data.txt<\/span> with the following text inside <span class=\"rnthl rntliteral\">MY ESP32 DATA<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>writeFile(LittleFS, \"\/data.txt\", \"MY ESP32 DATA \\r\\n\");<\/code><\/pre>\n\n\n\n<p>Something to notice about the <span class=\"rnthl rntliteral\">writeFile()<\/span> function: it creates a file (if it doesn&#8217;t exist) called <span class=\"rnthl rntliteral\">data.txt<\/span> with the text we define inside. <\/p>\n\n\n\n<p>If that file already exists, the <span class=\"rnthl rntliteral\">writeFile()<\/span> function will overwrite any existing contents inside that file. So, if you want to continuously add new data without replacing it, you should use the <span class=\"rnthl rntliteral\">appendFile()<\/span> function after creating the file. If you want to replace the content of the file, you should use the <span class=\"rnthl rntliteral\">writeFile()<\/span>.<\/p>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span>, we start by attributing a random value between 0 and 1000 to the <span class=\"rnthl rntliteral\">mydata<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>mydata = random (0, 1000);<\/code><\/pre>\n\n\n\n<p>Then, we append data to the file by calling the <span class=\"rnthl rntliteral\">appendFile()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>appendFile(LittleFS, \"\/data.txt\", (String(mydata)+ \"\\r\\n\").c_str()); \/\/Append data to the file<\/code><\/pre>\n\n\n\n<p>Notice that we concatenate the <span class=\"rnthl rntliteral\">mydata<\/span> variable with <span class=\"rnthl rntliteral\">&#8220;\\r\\n&#8221;<\/span> so that subsequent data is written on the next line. Because our variable is of <strong><em>int <\/em><\/strong>type, we need to convert it to a String before concatenating.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>String(mydata)<\/code><\/pre>\n\n\n\n<p>Additionally, then, we need to convert it to a const char using the <span class=\"rnthl rntliteral\">c_str()<\/span> method:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>String(mydata)+ \"\\r\\n\").c_str()<\/code><\/pre>\n\n\n\n<p>After appending data to the file, we&#8217;ll read its content by calling the <span class=\"rnthl rntliteral\">readFile()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>readFile(LittleFS, \"\/data.txt\"); \/\/ Read the contents of the file<\/code><\/pre>\n\n\n\n<p>New random values are generated and added to the file every 30 seconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>delay(30000);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Upload the code to your ESP32 board. Open the Serial Monitor at a baud rate of 115200. <\/p>\n\n\n\n<p>It should initialize the filesystem, create the file and start adding a new random number to the file every 30 seconds.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"601\" height=\"732\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Append-Data.png?resize=601%2C732&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Save Data to File LittleFS Example Serial Monitor\" class=\"wp-image-133991\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Append-Data.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Append-Data.png?resize=246%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 246w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n<p>Notice that if you restart your board, you&#8217;ll lose all your previous data. Why is that happening?<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"601\" height=\"732\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Append-Data-restart.png?resize=601%2C732&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Save Data to File LittleFS Example Serial Monitor\" class=\"wp-image-133992\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Append-Data-restart.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Append-Data-restart.png?resize=246%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 246w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n<p>That happens because we&#8217;re calling the <span class=\"rnthl rntliteral\">writeFile()<\/span> function in the <span class=\"rnthl rntliteral\">setup()<\/span>. As we&#8217;ve explained previously, it will create a new file if it doesn&#8217;t exist, or overwrite an already existing file with the same name. To prevent that, we can add some lines to the <span class=\"rnthl rntliteral\">setup()<\/span> to check whether the file already exists.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"check-if-file-exists-littlefs\">ESP32 with LittleFS &#8211; Check if a file already exists<\/h3>\n\n\n\n<p>To check if a file already exists in the filesystem, we can use the <span class=\"rnthl rntliteral\">exists()<\/span> method and pass as an argument the file path. You can add the following lines to the <span class=\"rnthl rntliteral\">setup()<\/span> to prevent overwriting when the ESP32 restarts:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Check if the file already exists to prevent overwritting existing data\nbool fileexists = LittleFS.exists(\"\/data.txt\");\nSerial.print(fileexists);\nif(!fileexists) {\n  Serial.println(\"File doesn\u2019t exist\");  \n  Serial.println(\"Creating file...\");\n  \/\/ Create File and add header\n  writeFile(LittleFS, \"\/data.txt\", \"MY ESP32 DATA \\r\\n\");\n}\nelse {\n  Serial.println(\"File already exists\");\n}<\/code><\/pre>\n\n\n\n<p>It uses the <span class=\"rnthl rntliteral\">exists()<\/span> method to check if the file already exists:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>bool fileexists = LittleFS.exists(\"\/data.txt\");<\/code><\/pre>\n\n\n\n<p>It will return <span class=\"rnthl rntliteral\">true<\/span> if the file already exists or <span class=\"rnthl rntliteral\">false<\/span> if it doesn&#8217;t.<\/p>\n\n\n\n<p>If it doesn&#8217;t exist, it will create the file with the content with define.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if(!fileexists) {\n  Serial.println(\"File doesn\u2019t exist\");\n  Serial.println(\"Creating file...\");\n  \/\/ Create File and add header\n  writeFile(LittleFS, \"\/data.txt\", \"MY ESP32 DATA \\r\\n\");\n}<\/code><\/pre>\n\n\n\n<p>If it already exists, it simply writes <span class=\"rnthl rntliteral\">File already exists<\/span> in the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>else {\n  Serial.println(\"File already exists\");\n}<\/code><\/pre>\n\n\n\n<p>Here&#8217;s the complete example that checks if the file already exists.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/\/ Project details: https:\/\/RandomNerdTutorials.com\/esp32-write-data-littlefs-arduino\/\n\n#include &lt;Arduino.h&gt;\n#include &quot;FS.h&quot;\n#include &lt;LittleFS.h&gt;\n\n\/* You only need to format LittleFS the first time you run a\n   test or else use the LITTLEFS plugin to create a partition\n   https:\/\/github.com\/lorol\/arduino-esp32littlefs-plugin\n *\/\n#define FORMAT_LITTLEFS_IF_FAILED true\n\nint mydata;\n\nvoid writeFile(fs::FS &amp;fs, const char * path, const char * message){\n    Serial.printf(&quot;Writing file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path, FILE_WRITE);\n    if(!file){\n        Serial.println(&quot;- failed to open file for writing&quot;);\n        return;\n    }\n    if(file.print(message)){\n        Serial.println(&quot;- file written&quot;);\n    } else {\n        Serial.println(&quot;- write failed&quot;);\n    }\n    file.close();\n}\n\nvoid appendFile(fs::FS &amp;fs, const char * path, const char * message){\n    Serial.printf(&quot;Appending to file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path, FILE_APPEND);\n    if(!file){\n        Serial.println(&quot;- failed to open file for appending&quot;);\n        return;\n    }\n    if(file.print(message)){\n        Serial.println(&quot;- message appended&quot;);\n    } else {\n        Serial.println(&quot;- append failed&quot;);\n    }\n    file.close();\n}\n\nvoid readFile(fs::FS &amp;fs, const char * path){\n    Serial.printf(&quot;Reading file: %s\\r\\n&quot;, path);\n\n    File file = fs.open(path);\n    if(!file || file.isDirectory()){\n        Serial.println(&quot;- failed to open file for reading&quot;);\n        return;\n    }\n\n    Serial.println(&quot;- read from file:&quot;);\n    while(file.available()){\n        Serial.write(file.read());\n    }\n    file.close();\n}\n\n\nvoid setup() {\n  Serial.begin(115200);\n  if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){\n      Serial.println(&quot;LittleFS Mount Failed&quot;);\n      return;\n   }\n   else{\n       Serial.println(&quot;Little FS Mounted Successfully&quot;);\n   }\n\n   \/\/ Check if the file already exists to prevent overwritting existing data\n   bool fileexists = LittleFS.exists(&quot;\/data.txt&quot;);\n   Serial.print(fileexists);\n   if(!fileexists) {\n       Serial.println(&quot;File doesn\u2019t exist&quot;);\n       Serial.println(&quot;Creating file...&quot;);\n       \/\/ Create File and add header\n       writeFile(LittleFS, &quot;\/data.txt&quot;, &quot;MY ESP32 DATA \\r\\n&quot;);\n   }\n   else {\n       Serial.println(&quot;File already exists&quot;);\n   }\n}\n\nvoid loop() {\n  mydata = random (0, 1000);\n  appendFile(LittleFS, &quot;\/data.txt&quot;, (String(mydata)+ &quot;\\r\\n&quot;).c_str()); \/\/Append data to the file\n  readFile(LittleFS, &quot;\/data.txt&quot;); \/\/ Read the contents of the file\n  delay(30000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP32\/ESP32_Write_File_LittleFS_Prevent_Overwrite.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>If you test this example, you&#8217;ll see that the file keeps all data even after a restart.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"601\" height=\"755\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Save-Data-Prevent-Overwrite.png?resize=601%2C755&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Save Data to File LittleFS Example Serial Monitor - prevent overwrite\" class=\"wp-image-133996\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Save-Data-Prevent-Overwrite.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-LittleFS-Save-Data-Prevent-Overwrite.png?resize=239%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 239w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>With this tutorial, you learned how to save data permanently on a file in the ESP32 LittleFS filesystem. You learn how to create a file, append data, and read the contents of a file.<\/p>\n\n\n\n<p>If you have a file with content that you want to save to the ESP32, and you don&#8217;t need to add data during runtime, you may want to use the LittleFS plugin instead. It allows you to save files that you have on your sketch folder directly to the ESP32 filesystem: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-littlefs-arduino-ide\/\">ESP32: Upload Files to LittleFS using Arduino IDE<\/a>.<\/p>\n\n\n\n<p>We hope you found this tutorial useful. Learn more about the ESP32 with our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE (eBook)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/build-web-servers-esp32-esp8266-ebook\/\">Build Web Servers with ESP32 and ESP8266 (eBook)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/firebase-esp32-esp8266-ebook\/\">Firebase Web App with ESP32 and ESP8266 (eBook)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32\/\">Free ESP32 Projects and Tutorials<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In this guide, you&#8217;ll learn how to write and save data permanently to a file saved on the ESP32 filesystem (LittleFS). LittleFS is a lightweight filesystem created for microcontrollers that &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP32: Write Data to a File (LittleFS) &#8211; Arduino IDE\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp32-write-data-littlefs-arduino\/#more-133987\" aria-label=\"Read more about ESP32: Write Data to a File (LittleFS) &#8211; Arduino IDE\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":134001,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[276,281,277,299,264],"tags":[],"class_list":["post-133987","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32","category-esp32-project","category-esp32-arduino-ide","category-0-esp32","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ESP32-Write-Data-To-a-File-LittleFS.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/133987","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=133987"}],"version-history":[{"count":16,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/133987\/revisions"}],"predecessor-version":[{"id":136731,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/133987\/revisions\/136731"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/134001"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=133987"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=133987"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=133987"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}