1 year, 10 months ago.

store integer in localfilesystem

Hey! I am working on a project where I want to save variables in Flash so that they do not get lost when the power goes out. for my project I am using a mbed 11u24. I thought to use localfilesystem to solve this. the only problem is that my variables are integers. Saving a string is pretty easy, but is there someone who knows how to save 6 separate integers and read back afterwards as separate numbers?

kind regards Jonas A.

1 Answer

1 year, 10 months ago.

Hello Jonas,

The following code worked for me on an LPC1768. I hope it will do also on an LPC11U24:

#include "mbed.h"

LocalFileSystem local("local");

int main()
    int myInt1 = 1;
    int myInt2 = 2;
    int myInt3 = 3;
    int myInt4 = 4;
    int myInt5 = 5;
    int myInt6 = 6;
    FILE*   fp = fopen("/local/myInts.bin", "w");
    putw(myInt1, fp);
    putw(myInt2, fp);
    putw(myInt3, fp);
    putw(myInt4, fp);
    putw(myInt5, fp);
    putw(myInt6, fp);
    myInt1 = 0;
    myInt2 = 0;
    myInt3 = 0;
    myInt4 = 0;
    myInt5 = 0;
    myInt6 = 0;
    fp = fopen("/local/myInts.bin", "r");
    fseek(fp, 0, SEEK_SET);    
    myInt1 = getw(fp);
    myInt2 = getw(fp);
    myInt3 = getw(fp);
    myInt4 = getw(fp);
    myInt5 = getw(fp);
    myInt6 = getw(fp);
    printf("myInt1 = %d\r\n", myInt1);
    printf("myInt2 = %d\r\n", myInt2);
    printf("myInt3 = %d\r\n", myInt3);
    printf("myInt4 = %d\r\n", myInt4);
    printf("myInt5 = %d\r\n", myInt5);
    printf("myInt6 = %d\r\n", myInt6);

Accepted Answer

One change: When opening the files use "wb" and "rb" for binary write/read access otherwise the file reads/writes may not work depending on the data content.

Or alternatively use fprintf(fp,"%i\r\n",myInt) and fscanf(fp,"%i\r\n",&myInt) to write and read the files as text. Slower and less efficient but it means the values will be easy to read/change if you plug the board into your computer.

posted by Andy A 09 Oct 2018

thank you Andy, the only minor problem is that the PUTW and GETW commands do not exist. I think this should be replaced by PUTC and GETC, then it works for bytes.

posted by Jonas Aertgeerts 10 Oct 2018

Probably the cleanest way to do it is to define some functions called putw and getw

void putw(int value, FILE *fp) {

int16_t getw(FILE *fp) { 
  int16_t result = getc(fp);
  result |= getc(fp)<<8;
  return result;

Although you need to be careful, the way Zoltan wrote the code is assuming that an int is 16 bits. On ARM it's probably 32 bits. Not an issue as long as you don't go over +/- 32k but if you do the saved value isn't going to match the value in memory.

The getw has to explicitly return an int16_t rather than an int otherwise negative values wouldn't come out correctly if the compiler is using 32 bit ints.

posted by Andy A 11 Oct 2018