Arm Mbed OS support forum

How to name a text file a variable

I’m trying to make a loop with a timer so that every 10 seconds the code writes a new text file and names it “log_file_001.txt”, “log_file_002.txt”, etc. I’m having an issue trying to convert an integer to a string

#include
#include “mbed.h”

Timer timer;
int n;

int main()
{
timer.start();
n=1; //set initial value of loop count

while(1) {

    if (timer.read_ms()>=10000) {
        n=n+1;
        timer.reset();
    }

    FILE *fp=fopen("/sd/mydir/log_file_00" + std::to_string(n) + “.txt”,“w”); //name file, open file to write
}

}

@Mackenzie_Fraser
Try something like this:
char fn_first_part[50] = {0};
char fn_second_part[10] = {0};

strcpy(fn_first_part, “/sd/mydir/log_file_00”);
strcpy(fn_second_part, std::to_string(n).c_str());
strcat(fn_second_part, “.txt”);
strcat(fn_first_part, fn_second_part);

then use
FILE *fp=fopen(fn_first_part,“w”);