I’m trying to append strings into a single file in the LittleFS system but running into issues with reading back what was appended. My code is as follows:
/*
* Project FS-Tester
* Description:
* Author:
* Date:
*/
#include <sys/stat.h>
#include <vector>
#include <fcntl.h>
// Initilize logger
SerialLogHandler logHandler1(LOG_LEVEL_INFO);
const char* fsPath = "/littlefstest/text";
// setup() runs once, when the device is first turned on.
void setup() {
// Put initialization like pinMode and begin functions here.
Serial.begin();
Particle.function("writeToFs",writeToFs);
Particle.function("dumpFs",dumpFs);
}
// loop() runs over and over again, as quickly as it can execute.
void loop() {
// The core of your code will likely live here.
}
int writeToFs(String command){
Log.info("Got new fs content");
Log.info(command);
command = command + ",";
int fd = open(fsPath, O_RDWR | O_CREAT | O_APPEND );
if(fd == -1){
Log.error("File failed to open");
return -5;
}
const char* req_event = command.c_str();
uint16_t size = strlen(req_event)+1;
int retVal = write(fd, req_event,size);
close(fd);
return retVal;
}
std::vector<String> parseArguments(String argumentString, String delimiter, int length){
char argumentBuf[length];
argumentString.toCharArray(argumentBuf, length);
std::vector<String> result;
char * pch;
pch = strtok (argumentBuf,delimiter);
while (pch != NULL)
{
result.push_back(pch);
pch = strtok (NULL,delimiter);
}
return result;
}
int dumpFs(String command){
//Get File Stats
int fd = open(fsPath, O_RDWR );
if(fd == -1){
Log.error("File failed to open");
return -5;
}
uint16_t len;
struct stat fStatBuf;
int fStatRetVal = stat(fsPath, &fStatBuf);
if(fStatRetVal == -1 ){
Log.error("fStat on offline cache failed");
return SYSTEM_ERROR_FILE;
} else {
Log.info("Got stat, reading...");
len = fStatBuf.st_size;
}
Log.info("File was of size: %ld",len);
//Read and Parse File
char offlineCacheString[len];
int readRetVal = read(fd, offlineCacheString, sizeof(offlineCacheString));
if(readRetVal <= 0){
Log.error("read on offline cache failed");
return SYSTEM_ERROR_FILE;
}
Log.info("Size of read: %ld",readRetVal);
Log.info("File read:");
Log.info(offlineCacheString);
std::vector<String> entries = parseArguments(String(offlineCacheString),",",readRetVal);
// Publish cached data vector
for(int i=0; i< entries.size(); i++){
Log.info(entries[i]);
}
truncate(fsPath,0);
close(fd);
return readRetVal;
}
If I send three commands to ‘writeToFs’ say ‘hello’ ‘world’ ‘test’. I would expect a call to ‘dumpFs’ to log “hello,world,test,” before reporting the parse version. When I run it, I only get back the “hello,” value. Any thoughts on why this is the case? I suspect I’m using the O_APPEND flag incorrectly or may need to use lseek but would appreciate some advice.