AnsweredAssumed Answered

FATFS SDIO auto-increment File Name problem

Question asked by j.martin on Dec 13, 2015
Latest reply on Dec 20, 2015 by j.martin
Hello all,

I am new here and struggling to write a clean for creating a file with auto-increment name after the power on. My purpose is to save buffer data in .BIN format, power off system, start a new session when necessary and save new sensor data in new .BIN file. I have started in this way:

FRESULT res;
FILINFO fno;
FIL fil;
DIR dir;
FATFS fs32;
char* path = "";
UINT BytesWritten;          // SD card write Byte Count
uint16_t ReceiveData_16[8192];   // 16-bit Data Buffer

#if _USE_LFN
        static char lfn[_MAX_LFN + 1];
#endif

#if _USE_LFN
        fno.lfname = lfn;
        fno.lfsize = sizeof(lfn);
#endif

void SD_Write(void)
{        
    char str[];
    char *s = str;
    char *fn;
    
    if (f_opendir(&dir, path)== FR_OK)  
    {
      while(1)
      {                  
        res = f_readdir(&dir, &fno);   // Read Directory for all files
        if ((res != FR_OK) || (fno.fname[0] == 0))  // Break loop after all file read
          break;

#if _USE_LFN
        fn = *fno.lfname ? fno.lfname : fno.fname;  // Store File Names
#else
        fn = fno.fname;
#endif
    strcpy(s, fn);  
      }                 
    }
        
        len= strlen(s);
        
        // Need to increment file name, say, "073.BIN" to "074.BIN" file
        
        if (s[len-5]=='9')  
        {
            s[len-5]='0';        
            if (s[len-6]=='9')
            {
                s[len-6]='0';    
            }
            else
            {
                s[len-6]=s[len-6]+1;
            }        
        }
        else
        {        
        s[len-5]=s[len-5]+1;
        }

        //Buffer write with new file name
        
 if (f_open(&fil, str, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)
 {
    f_lseek(&fil, fil.fsize);
    f_write(&fil, ReceiveData_16, sizeof(ReceiveData_16), &BytesWritten);
    f_close(&fil);
 }
}


The issue is it'll not work with a blank directory. Can anyone suggest me a clean code in this regard. I apologize for my poor coding logic.

Thank you for your time.

Outcomes