Skip to main content
Visitor II
October 21, 2021
Solved

How to get USB stick free size in FAT file system?

  • October 21, 2021
  • 2 replies
  • 894 views

Hi,

I am working to make application of USB host. At initial stage, I need to read how big is the free size of attached USB stick using the FAT file system middle ware. Can someone give me some pointer which FAT system interface I can use? I know how to mount and dismount, but not sure how to get this USB stick free size.

    This topic has been closed for replies.
    Best answer by KnarfB

    f_getfree ? http://elm-chan.org/fsw/ff/doc/getfree.html

    hth

    KnarfB

    2 replies

    KnarfBAnswer
    Super User
    October 21, 2021
    Graduate II
    October 21, 2021
    void printsize(uint32_t size, char *s)
    {
     if (size >= 1000000) // Storage vendor math
     printf(" %6.1lf GB %s\n", (double)size / 1000000.0, s);
     else if (size >= 1000)
     printf(" %6.1lf MB %s\n", (double)size / 1000.0, s);
     else
     printf(" %6.1lf KB %s\n", (double)size, s);
    }
     
     
    {
     FATFS *fs;
     DWORD fre_clust, fre_sect, tot_sect;
     
     /* Get volume information and free clusters of drive 1 */
     
     res = f_getfree("", &fre_clust, &fs);
     
     if (res != FR_OK)
     {
    #ifdef DBG
     printf("res = %d f_getfree\n", res);
    #endif
     return;
     }
     
     switch(fs->fs_type)
     {
     case FS_FAT12 : puts("FAT12"); break;
     case FS_FAT16 : puts("FAT16"); break;
     case FS_FAT32 : puts("FAT32"); break;
     case FS_EXFAT : puts("EXFAT"); break;
     default : puts("Unknown FAT");
     }
     
     /* Get total sectors and free sectors */
     tot_sect = (fs->n_fatent - 2) * fs->csize;
     fre_sect = fre_clust * fs->csize;
     
     /* Print the free space (assuming 512 bytes/sector) */
     printsize(tot_sect / 2, "total drive space");
     printsize(fre_sect / 2, "available");
     printsize((tot_sect - fre_sect) / 2, "used");
    }