Teensy4: Using LittleFS from C (not C++) via the Arduino IDE

ChrisCurl

Active member
I have a Forth system I have written in C that is as portable as I can make it, meaning that it can run under Windows, Linux and on development boards, including the Teensy 4.

My next step is to try to create a C wrapper for the 4 simple functions that provide most basic file access functionality using LittleFS:

handle = fopen(filename, mode)
close(handle)
count = fread(addr,sz,num,handle)
count = fwrite(addr,sz,num,handle)

That is all is needed, just those 4 functions. The thing is, this needs to be in C, not C++ to fit in with the rest of the system.

I know that the functionality is all there in the LittleFS library.

Might there already a C wrapper I can use?
Or ... how would I go about creating a C wrapper for LittleFS?
 
Here is what I came up with ... how's it look?

C:
#if defined (_LITTLEFS_)
  #include <LittleFS.h>
  LittleFS_Program myFS;
  void fileInit() {
      myFS.begin(1 * 1024 * 1024);
      printString("\r\nLittleFS: initialized");
      printStringF("\r\nBytes Used: %llu, Bytes Total:%llu", myFS.usedSize(), myFS.totalSize());
  }
  cell_t fOpen(cell_t nm, cell_t md) { y=(char*)md; File x=myFS.open((char*)nm,*y=='w'?FILE_WRITE:FILE_READ); return (cell_t)x; }
  void   fClose(cell_t fp) { File x=File((FileImpl*)fp); x.close(); }
  cell_t fRead(cell_t addr, cell_t sz, cell_t num, cell_t fp) { File x=File((FileImpl*)fp); return x.read((char*)addr,(sz*num)); }
  cell_t fWrite(cell_t addr, cell_t sz, cell_t num, cell_t fp) { File x=File((FileImpl*)fp); return x.write((char*)addr,(sz*num)); }
#else
  static void nf() { printString("-noFile-"); }
  void   fileInit() { }
  cell_t fOpen(cell_t nm, cell_t md) { nf(); return 0; }
  void   fClose(cell_t fp) { nf(); }
  cell_t fRead(cell_t addr, cell_t sz, cell_t num, cell_t fp) { nf(); return 0; }
  cell_t fWrite(cell_t addr, cell_t sz, cell_t num, cell_t fp) { nf(); return 0; }
#endif
 
Remember in Arduino's definitions FILE_WRITE appends. If you want "normal" write that starts at offset 0 (overwriting anything already at the beginning of the file), use FILE_WRITE_BEGIN.
 
Remember in Arduino's definitions FILE_WRITE appends. If you want "normal" write that starts at offset 0 (overwriting anything already at the beginning of the file), use FILE_WRITE_BEGIN.
Thanks. I was looking at FS.h, and the File object looks like it doesn't have a similar to fgets() to read a line of text... is there one that I am missing?

I can write one myself of course, but if there is something that I am just missing ... all the better!
 
Back
Top