C++ streams with ChaN FatFS?

Status
Not open for further replies.

JKIM

Active member
I have been banging my head on this for days, especially since I would have thought it would be a common question!
I'm trying to serialize some objects to store them onto the SD card in a Teensy4.

My project is *not* using SD.h/SdFat because we are using a different toolchain (SdFat collides with stdio.h, but that is a whole other adventure).

I have FatFS working with the SD card, but my serializer (ThorsSerializer) works with iostreams.
It seems that FatFS has it's own implementation of fopen style access, and does not implement streams access. I can't find any ARM based resources that have wrapped streams around FatFS.

So, after research, I found the suggestions to use funopen() of fopencookie(), which can be wrapped around the FatFS functions. This gets me a FILE from FIL.
Now I tried converting this FILE stream to an ostream, but it hasn't been working yet and seems overly complicated...

So is there any suggestions or examples that folks have seen to get streams implemented on FatFS?

Here is my attempt thus far, but there has to be a better way!:

Code:
#include <ff.h>
#include <stdio.h>
#include <ext/stdio_filebuf.h>

FIL g_fileObject; /* File object */
FILE * f;

int my_writefn(void * cookie, const char * data, int n) {
  f_write(&g_fileObject, data, n, nullptr);
  return 0;
}

int my_readfn(void * cookie, char * data, int n) {
	return 0;
}

fpos_t my_seekfn(void * cookie, fpos_t offset, int whence) {
	return 0;
}

int my_closefn(void * cookie) {

	f_close(&g_fileObject);
	return 0;
}


f_open(&g_fileObject, _T("/filetest.txt"), FA_WRITE | FA_READ | FA_CREATE_ALWAYS);

f = funopen(NULL, my_readfn, my_writefn, my_seekfn, my_closefn);

__gnu_cxx::stdio_filebuf<char> fbuf(f, std::ios::in|std::ios::out|std::ios::app);
std::ostream fs(&fbuf);

fs << "Hello World\n";
fs << std::flush;
fclose(f);
 
Status
Not open for further replies.
Back
Top