This is how I would do it. This code compiles but I didn't run it on a device but it's probably close.
#include <fcntl.h>
#include <sys/stat.h>
int storeString(const char *fileName, const String &data)
{
int resultLen = -1;
int fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC);
if (fd != -1) {
resultLen = write(fd, data.c_str(), data.length());
close(fd);
}
return resultLen;
}
int readString(const char *fileName, String &result)
{
int resultLen = -1;
result = "";
int fd = open(fileName, O_RDONLY);
if (fd != -1) {
struct stat sb = {0};
fstat(fd, &sb);
resultLen = sb.st_size;
if (resultLen > 0) {
char *buf = new char[resultLen + 1];
if (buf) {
resultLen = read(fd, buf, resultLen);
if (resultLen >= 0) {
buf[resultLen] = 0;
result = buf;
}
delete[] buf;
}
}
else {
resultLen = 0;
}
close(fd);
}
return resultLen;
}
The filename is const char * instead of String because it won't be modified. You can still pass a String as a parameter if you want when calling it.
I changed readString to take a String& (String by reference) which is filled in with the data. This eliminates the need to pre-define how big of a buffer to use.
The inside of readString() uses fstat to determine the length of the file, which determines how much buffer is needed.