Try this
myFile = SD.open("/sys/ram.txt", "a+");
The critical factor is you're using ESP32. The file mode macros in the platform-specific lower-level FS
library are
#define FILE_READ "r"
#define FILE_WRITE "w"
#define FILE_APPEND "a"
In contrast, Uno (for example) uses the "root level" generic SD
library, which has only two modes
#define FILE_READ O_READ
#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)
where WRITE
includes READ
(and APPEND
). But on ESP32, they're entirely separate. With "w"
alone, read()
always returns -1
. Drill in far enough, and the implementation uses good old fopen
if (!stat(temp, &_stat)) {
//file found
if (S_ISREG(_stat.st_mode)) {
_isDirectory = false;
_f = fopen(temp, mode);
There's a nice table at std::fopen - cppreference.com that tells you what you need; an excerpt
File access mode string |
Meaning |
Explanation |
Action if file already exists |
w |
write |
Create a file for writing |
destroy contents |
r+ |
read extended |
Open a file for read/write |
read from start |
w+ |
write extended |
Create a file for read/write |
destroy contents |
a+ |
append extended |
Open a file for read/write |
write to end |
"r+"
fails if the file does not exist, so you probably want "a+"
. As mentioned by @markd833 a week ago, either "w"
or "w+"
erases an existing file. Sadly the ESP32 FS library makes no mention of these extended modes, nor provides any support for them. So you need to manually spell the mode string.
Apparently on ESP32, there's a poorly named optional third argument: create
File open(const char* path, const char* mode = FILE_READ, const bool create = false);
which when enabled
////file not found but mode permits file creation and folder creation
if ((mode && mode[0] != 'r') && create) {
will loop through and create each path segment. Didn't try it.