1

I did not the understand how to get file names in SD card using FATFS. I am able to read and write .txt files with this code below:

if (f_mount(&fatfs, SDPath, 1) == FR_OK) {
    /* Write Test */
    res = f_open(&file, (const TCHAR*)"TESTTEST.TXT", FA_WRITE | FA_CREATE_ALWAYS);
    res = f_write(&file, txtWriteBuf, strlen((const char*)txtWriteBuf), &bytesW);
    res = f_close(&file);
    /* Read Test */
    res = f_open(&file, (const TCHAR*)"TESTTEST.TXT", FA_READ);
    res = f_read(&file, txtReadBuf, f_size(&file), &bytesR);
    res = f_close(&file);

    /* File Listing Code */
    ???

    /* LCD Display Code */
    ...
    /* My LCD Codes Here */
}

After that I want to list these file names on my LCD screen. I am stuck at getting files names in root directory. I want these files to be listed on my LCD. And I have no idea about how to use f_opendir(...), f_readdir(...) etc. How to do it in correct way?

daaarwiin
  • 127
  • 1
  • 13
  • Did you read the documentation, and searched for tutorials? – the busybee Oct 13 '21 at 08:43
  • Research POSIX `opendir` and `readdir()` functions, like https://pubs.opengroup.org/onlinepubs/009696799/functions/readdir_r.html , you'll find many examples. But there's an example in dosc: http://elm-chan.org/fsw/ff/doc/readdir.html ... – KamilCuk Oct 13 '21 at 08:44
  • @KamilCuk that sounds like a bad idea considering he hadn't specified if the scope of his program is limited to POSIX compatible environments. – user426 Oct 13 '21 at 09:00

1 Answers1

0

First define DIR and FILINFO structures:

DIR dir;                    // Directory
FILINFO fno;                // File Info

Then you can use the following code as sample:

f_opendir(&dir, "/");   // Open Root
do
{
    f_readdir(&dir, &fno);
    if(fno.fname[0] != 0)
        printf("File found: %s\n", fno.fname); // Print File Name
} while(fno.fname[0] != 0);

f_closedir(&dir);

Also you can add error checks to be consistent, I use my own assert therefore omitted.

For Long File Name _USE_LFN in ffconf.h has to be set to 1. Also you need to declare buffer e.g. TCHAR lfname[_MAX_LFN];. Afterwards assign the buffer and its size in your code:

fno.lfname = lfname;
fno.lfsize = _MAX_LFN - 1;

Finaly you can replace fname with lfname in the code provided above.

Creek Drop
  • 464
  • 3
  • 13