4 years, 7 months ago.

How to write a char array to a file

Dear experts

I have an array of chars. I want to write this array to a log file on the flash storage. The code must work for any length of array. I already tried some stuff, but none of them worked for me. In best case, I want to form an array of chars or a string which can be written to the flash in one time.

Code

#include "mbed.h"

LocalFileSystem local("local");

#define ROOT_PATH "/local/"
const char log_file[] = ROOT_PATH "log.ini";

unsigned char myArray [] = {0, 50, 100, 150, 200};

int Main()
{
   FILE *fp = fopen(log_file, "w");  
   fprintf(fp, "Start of log file\r\n");
   fclose(fp);

   //Some code I can't find
   //
   //

   while(1)
   {

   }
}

Output:
Start of log file
array: 0 50 100 150 200

Thank you

1 Answer

4 years, 7 months ago.

Hello Jordy,

The following program works fine on my LPC1768 Mbed board when built with Mbed OS-5.13.2:

#include "mbed.h"

LocalFileSystem local("local"); // Create the local filesystem under the name "local"

int main()
{
    FILE*   fp = fopen("/local/log.ini", "w");  // Open "log.ini" text file on the local file system for writing

    fprintf(fp, "Hello World!");                // Write "Hello World!" C-style string (terminated with 0) to the "log.ini" text file
    fclose(fp);                                 // Close the "log.ini" text file
}
  • To make it work, after flashing disconnect and then reconnect the USB cable to the Mbed board. You should then see the log.ini file on the MBED virtual disk and be able to open it in you favorite text editor.
  • Please notice that the "w" mode creates a text file for writing or truncates it to zero length. The character array to store shall be a C-style string (= character array terminated with 0 character). Because myArray in the example program above starts with 0 character it cannot be stored in such text file.
  • To store binary data use the "wb" mode as advised here. For example:

#include "mbed.h"

LocalFileSystem local("local"); // Create the local filesystem under the name "local"
unsigned char   myArray[] = { 0, 50, 100, 150, 200 };

int main()
{
    FILE*   fp = fopen("/local/log.ini", "wb"); // Open "log.ini" binary file on the local file system for writing

    // Write myArray to the file.
    for (size_t i = 0; i < sizeof(myArray) / sizeof(myArray[0]); i++)
        fputc(myArray[i], fp);                  // Write an unsigned char (byte) from myArray to the file

    fclose(fp);                                 // Close the "log.ini" binary file
}