I am using one of the Examples sketches, which I modified, in the IDE 2.x which creates a USB drive visible to the client (a Windows Laptop in my case) over the USB cable. The example I used was the RP2040_DataLogger_FIFO example. I stripped it down to just write a few lines of text into a file and I verified that I could see the USB device.
The code below creates the USBMSD instance, mounts the file system "/fs/" and uses stdio.h to open and write to a file. What I found is that the fflush() does nothing. You can have this there, or not. It won't matter to the end result. If, however, you don't put the fclose(), then nothing appears in the file seen by the Windows client. The USB drive is visible (as the D: drive), and the file exists, but its empty.
For more complex examples it seems like I am forced to open the file, write to it (use the "a+" mode) and then close it immediately. This is a hack which seems to allow me to write an arbitrary number of lines of text. My question is simply...shouldn't fflush() be pushing the writes into the file seen by the Windows client real-time? Why does fflush() not work, and why is fclose() required to do this. It seems like only the fclose() is actually flushing data to the Flash? Am I missing something?
#include "PluggableUSBMSD.h"
#include "FlashIAPBlockDevice.h"
#include "WiFiNINA.h"
static FlashIAPBlockDevice bd(XIP_BASE + 0x100000, 0x100000);
USBMSD MassStorage(&bd);
void USBMSD::begin()
{
int err = getFileSystem().mount(&bd);
if (err) {
err = getFileSystem().reformat(&bd);
}
}
mbed::FATFileSystem &USBMSD::getFileSystem()
{
static mbed::FATFileSystem fs("fs");
return fs;
}
FILE *fileptr=nullptr;
int count=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
MassStorage.begin();
char mystr[16]="hello there!\n";
char filename[32];
snprintf(filename, 16, "/fs/data.txt");
fileptr = fopen(filename, "w+");
fprintf(fileptr, "This was a test %d\n", count++);
fflush(fileptr);
fprintf(fileptr,"So was this...%d\n",count);
fflush(fileptr);
fclose(fileptr);
}
void loop() {
}