XDK API  3.6.0
Documentation
Files | Data Structures | Enumerations | Functions
FAT File System

FatFS Documentation. More...

Files

file  diskio.h
 
file  ff.h
 

Data Structures

struct  DIR
 
struct  FATFS
 
struct  FIL
 
struct  FILINFO
 

Enumerations

enum  DRESULT
 
enum  FRESULT
 

Functions

DSTATUS disk_initialize (BYTE pdrv)
 The disk_initialize function initializes the storage device. More...
 
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void *buff)
 The disk_ioctl function cntrols device specific features and miscellaneous functions other than generic read/write. More...
 
DRESULT disk_read (BYTE pdrv, BYTE *buff, DWORD sector, UINT count)
 The disk_read function reads sector(s) from the storage device. More...
 
DSTATUS disk_status (BYTE pdrv)
 The disk_status function returns the current drive status. More...
 
DRESULT disk_write (BYTE drv, const BYTE *buff, DWORD sector, UINT count)
 The disk_write writes sector(s) to the storage device. More...
 
FRESULT f_chdir (const TCHAR *path)
 The f_chdir function changes the current directory of a drive. More...
 
FRESULT f_chdrive (const TCHAR *path)
 The f_chdrive function changes the current drive. More...
 
FRESULT f_chmod (const TCHAR *path, BYTE attr, BYTE mask)
 The f_chmod function changes the attribute of a file or sub-directory. More...
 
FRESULT f_close (FIL *fp)
 The f_close function closes an open file. More...
 
FRESULT f_closedir (DIR *dp)
 The f_closedir function closes an open directory. More...
 
int f_eof (FIL *fp)
 The f_eof function tests for end-of-file on a file. More...
 
int f_error (FIL *fp)
 The f_error tests for an error on a file. More...
 
FRESULT f_fdisk (BYTE pdrv, const DWORD part[], void *work)
 The f_fdisk fucntion divides a physical drive. More...
 
FRESULT f_forward (FIL *fp, UINT(*func)(const BYTE *, UINT), UINT btf, UINT *bf)
 The f_forward function reads the file data and forward it to the data streaming device. More...
 
FRESULT f_getcwd (TCHAR *buff, UINT len)
 The f_getcwd function retrieves the current directory. More...
 
FRESULT f_getfree (const TCHAR *path, DWORD *nclst, FATFS **fatfs)
 The f_getfree function gets number of the free clusters on the volume. More...
 
FRESULT f_getlabel (const TCHAR *path, TCHAR *label, DWORD *vsn)
 The f_getlabel function returns volume label and volume serial number of a drive.
Example: More...
 
TCHARf_gets (TCHAR *buff, int len, FIL *fp)
 The f_gets reads a string from the file. More...
 
FRESULT f_lseek (FIL *fp, DWORD ofs)
 The f_lseek function moves the file read/write pointer of an open file object. It can also be used to expand the file size (cluster pre-allocation). More...
 
FRESULT f_mkdir (const TCHAR *path)
 The f_mkdir function creates a new directory. More...
 
FRESULT f_mkfs (const TCHAR *path, BYTE sfd, UINT au)
 The f_mkfs fucntion creates an FAT file system on the logical drive. More...
 
FRESULT f_mount (FATFS *fs, const TCHAR *path, BYTE opt)
 The f_mount fucntion registers/unregisters file system object to the FatFs module. More...
 
FRESULT f_open (FIL *fp, const TCHAR *path, BYTE mode)
 The f_open function creates a file object to be used to access the file. More...
 
FRESULT f_opendir (DIR *dp, const TCHAR *path)
 The f_opendir function opens a directory. More...
 
int f_printf (FIL *fp, const TCHAR *fmt,...)
 The f_printf function writes formatted string to the file. More...
 
int f_putc (TCHAR chr, FIL *fp)
 The f_putc funciton puts a character to the file. More...
 
int f_puts (const TCHAR *str, FIL *fp)
 The f_puts function writes a string to the file. More...
 
FRESULT f_read (FIL *fp, void *buff, UINT btr, UINT *br)
 The f_read function reads data from a file. More...
 
FRESULT f_readdir (DIR *dp, FILINFO *fno)
 The f_readdir function reads directory entries. More...
 
FRESULT f_rename (const TCHAR *old_name, const TCHAR *new_name)
 Renames a file or sub-directory. More...
 
FRESULT f_setlabel (const TCHAR *label)
 The f_setlabel function sets/removes the label of a volume. More...
 
DWORD f_size (FIL *fp)
 The f_size function gets the size of a file. More...
 
FRESULT f_stat (const TCHAR *path, FILINFO *fno)
 The f_stat function checks the existence of a file or sub-directory. More...
 
FRESULT f_sync (FIL *fp)
 The f_sync function flushes the cached information of a writing file. More...
 
DWORD f_tell (FIL *fp)
 The f_tell function gets the current read/write pointer of a file. More...
 
FRESULT f_truncate (FIL *fp)
 The f_truncate function truncates the file size. More...
 
FRESULT f_unlink (const TCHAR *path)
 The f_unlink function removes a file or sub-directory. More...
 
FRESULT f_utime (const TCHAR *path, const FILINFO *fno)
 The f_utime function changes the timestamp of a file or sub-directory. More...
 
FRESULT f_write (FIL *fp, const void *buff, UINT btw, UINT *bw)
 The f_write writes data to a file. More...
 
DWORD get_fattime (void)
 The get_fattime function gets current time. More...
 

Detailed Description

FatFs - Generic FAT File System Module

FatFs is a generic FAT file system module for small embedded systems. The FatFs is written in compliance with ANSI C and completely separated from the disk I/O layer. Therefore it is independent of hardware architecture. It can be incorporated into small microcontrollers with limited resource, such as AVR, 8051, PIC, ARM, Z80, 68k and etc.

Features:

layers.jpg

Device Control Interface

Since the FatFs module is a file system layer, it is completely separated from physical devices, such as memory card, harddisk and any type of storage devices. FatFs access the storage device via a simple interface described below. The low level device control module is not a part of FatFs module. It is provided by implementer. Also sample implementations for some platforms are available in the downloads.


Data Structure Documentation

struct DIR
+ Collaboration diagram for DIR:

Data Fields

DWORD clust
 
BYTEdir
 
BYTEfn
 
FATFSfs
 
WORD id
 
WORD index
 
WCHARlfn
 
WORD lfn_idx
 
DWORD sclust
 
DWORD sect
 

Field Documentation

DWORD clust
BYTE* dir
BYTE* fn
FATFS* fs
WORD id
WORD index
WCHAR* lfn
WORD lfn_idx
DWORD sclust
DWORD sect
struct FATFS

Data Fields

BYTE csize
 
DWORD database
 
DWORD dirbase
 
BYTE drv
 
DWORD fatbase
 
DWORD free_clust
 
BYTE fs_type
 
BYTE fsi_flag
 
DWORD fsize
 
WORD id
 
DWORD last_clust
 
DWORD n_fatent
 
BYTE n_fats
 
WORD n_rootdir
 
_SYNC_t sobj
 
DWORD volbase
 
BYTE wflag
 
BYTE win [_MAX_SS]
 
DWORD winsect
 

Field Documentation

BYTE csize
DWORD database
DWORD dirbase
BYTE drv
DWORD fatbase
DWORD free_clust
BYTE fs_type
BYTE fsi_flag
DWORD fsize
WORD id
DWORD last_clust
DWORD n_fatent
BYTE n_fats
WORD n_rootdir
_SYNC_t sobj
DWORD volbase
BYTE wflag
BYTE win[_MAX_SS]
DWORD winsect
struct FIL
+ Collaboration diagram for FIL:

Data Fields

BYTE buf [_MAX_SS]
 
DWORD clust
 
BYTEdir_ptr
 
DWORD dir_sect
 
DWORD dsect
 
BYTE err
 
BYTE flag
 
DWORD fptr
 
FATFSfs
 
DWORD fsize
 
WORD id
 
DWORD sclust
 

Field Documentation

BYTE buf[_MAX_SS]
DWORD clust
BYTE* dir_ptr
DWORD dir_sect
DWORD dsect
BYTE err
BYTE flag
DWORD fptr
FATFS* fs
DWORD fsize
WORD id
DWORD sclust
struct FILINFO

Data Fields

BYTE fattrib
 
WORD fdate
 
TCHAR fname [13]
 
DWORD fsize
 
WORD ftime
 
TCHARlfname
 
UINT lfsize
 

Field Documentation

BYTE fattrib
WORD fdate
TCHAR fname[13]
DWORD fsize
WORD ftime
TCHAR* lfname
UINT lfsize

Enumeration Type Documentation

enum DRESULT
Enumerator
RES_OK 
RES_ERROR 
RES_WRPRT 
RES_NOTRDY 
RES_PARERR 
enum FRESULT
Enumerator
FR_OK 
FR_DISK_ERR 
FR_INT_ERR 
FR_NOT_READY 
FR_NO_FILE 
FR_NO_PATH 
FR_INVALID_NAME 
FR_DENIED 
FR_EXIST 
FR_INVALID_OBJECT 
FR_WRITE_PROTECTED 
FR_INVALID_DRIVE 
FR_NOT_ENABLED 
FR_NO_FILESYSTEM 
FR_MKFS_ABORTED 
FR_TIMEOUT 
FR_LOCKED 
FR_NOT_ENOUGH_CORE 
FR_TOO_MANY_OPEN_FILES 
FR_INVALID_PARAMETER 

Function Documentation

DSTATUS disk_initialize ( BYTE  pdrv)

This function initializes the storage device and put it ready to generic read/write. When the function succeeded, STA_NOINIT flag in the return value is cleared.
Application program MUST NOT call this function, or FAT structure on the volume can be broken. To re-initialize the file system, use f_mount() function instead. This function is called at volume mount process by FatFs module to manage the media change.

Parameters
[in]pdrvPhysical drive number to identify the target device. Always zero at single drive system.
Return values
Thisfunction returns the current drive status flags as the result. For details of the drive status, refer to the disk_status() function.
DRESULT disk_ioctl ( BYTE  pdrv,
BYTE  cmd,
void *  buff 
)

The FatFs module requires only five device independent commands described below.

Standard ioctl command used by FatFs:
Command Description
CTRL_SYNC Make sure that the device has finished pending write process. If the disk I/O module has a write back cache, the dirty buffers must be written back to the media immediately. Nothing to do for this command if each write operation to the media is completed within the disk_write() function.
GET_SECTOR_COUNT Returns number of available sectors on the drive into the DWORD variable pointed by buff. This command is used by only f_mkfs() and f_fdisk() function to determine the volume/partition size to be created. Required at _USE_MKFS == 1 or _MULTI_PARTITION == 1.
GET_SECTOR_SIZE Returns sector size of the media into the WORD variable pointed by buff. Valid return values of this command are 512, 1024, 2048 and 4096. This command is required only at variable sector size configuration, _MAX_SS > _MIN_SS. At fixed sector size configuration, _MAX_SS == _MIN_SS, this command is not used and the device must work at that sector size.
GET_BLOCK_SIZE Returns erase block size of the flash memory media in unit of sector into the DWORD variable pointed by buff. The allowable value is from 1 to 32768 in power of 2. Return 1 if the erase block size is unknown or non flash memory media. This command is used by only f_mkfs() function and it attempts to align data area to the erase block boundary. Required at _USE_MKFS == 1.
CTRL_TRIM Informs the device the data on the block of sectors that specified by DWORD array {<start sector>="">, <end sector>="">} pointed by buff is no longer needed and it may be erased. This is an identical command to Trim of ATA device. When this feature is not supported or not a flash memory device, nothing to do for this command. The FatFs does not check the result code and the file function is not affected even if the sector block was not erased well. This command is called on removing a cluster chain and f_mkfs() function. Required at _USE_TRIM == 1.

FatFs never uses any device dependent command nor user defined command. Following table shows an example of non-standard commands usable for some applications.

Example of optional ioctl command
Command Description
CTRL_FORMAT Create a physical format on the media. If buff is not null, it is pointer to the call-back function for progress notification.
CTRL_POWER_IDLE Put the device idle state. STA_NOINIT in status flag may not be set if the device goes active state by generic read/write function.
CTRL_POWER_OFF Put the device off state. Shut-down the power to the device and deinitialize the device interface if needed. STA_NOINIT in status flag must be set. The device goes active state by disk_initialize() function.
CTRL_LOCK Lock media eject mechanism.
CTRL_UNLOCK Unlock media eject mechanism.
MMC_GET_CSD Eject media cartridge. STA_NOINIT and STA_NODISK in status flag are set after the function succeeded.
MMC_GET_CID Get card type. The type flags, bit0:MMCv3, bit1:SDv1, bit2:SDv2+ and bit3:LBA, is stored to a BYTE variable pointed by buff. (MMC/SDC specific command)
MMC_GET_OCR Get OCR register into a 4-byte buffer pointed by buff. (MMC/SDC specific command)
MMC_GET_SDSTAT Get SDSTATUS register into a 64-byte buffer pointed by buff. (SDC specific command)
ATA_GET_REV Get the revision string into a 16-byte buffer pointed by buff. (ATA/CFC specific command)
ATA_GET_MODEL Get the model string into a 40-byte buffer pointed by buff. (ATA/CFC specific command)
ATA_GET_SN Get the serial number string into a 20-byte buffer pointed by buff. (ATA/CFC specific command)
Parameters
[in]pdrvPhysical drive number to identify the target device.
[in]cmdCommand code.
[in,out]buffPointer to the parameter depends on the command code. Do not care if no parameter to be passed.
Return values
RES_OK(0)
The function succeeded.
RES_ERROR
An error occured.
RES_PARERR
The command code or parameter is invalid.
RES_NOTRDY
The device has not been initialized.
Note
The disk_ioctl function is not needed when _FS_READONLY == 1 and _MAX_SS == _MIN_SS.
DRESULT disk_read ( BYTE  pdrv,
BYTE buff,
DWORD  sector,
UINT  count 
)

The data read/write operation to the storage devices is done in unit of sector. FatFs supports the sector size in range of from 512 to 4096 bytes. When FatFs is configured to fixed sector size (_MIN_SS == MAX_SS, this will be the most case), the read/write function must work at that sector size. If variable sector size is selected (_MIN_SS < MAX_SS), FatFs inquires the sector size with disk_ioctl() after initialization.
The memory address specified by buff is not that always aligned to word boundary because the argument is defined as BYTE*. The misaligned read/write request can occure at direct transfer. If the bus architecture, especially DMA controller, does not allow misaligned memory access, it should be solved in this function. There are some workarounds described below to avoid this issue.

  • Convert word transfer to byte transfer in this function if needed. - Recommended.
  • For f_read(), avoid long read request that includes a whole of sector. - Direct transfer will never occure.
  • For f_read(fp, buff, btr, &br), make sure that (((UINT)buff & 3) == (f_tell(fp) & 3)) is true. - Word aligned direct transfer is guaranteed.
    Generally, a multiple sector transfer request must not be split into single sector transactions to the storage device, or you will not get good read throughput.
    Parameters
    [in]pdrvPhysical drive number to identify the target device.
    [out]buffPointer to the byte array to store the read data.
    [in]sectorStart sector number in 32-bit LBA.
    [in]countNumber of sectors to read in range of from 1 to 128..
    Return values
    RES_OK(0)
    The function succeeded.
    RES_ERROR
    Any hard error occured during the read operation and could not recover it.
    RES_PARERR
    Invalid parameter.
    RES_NOTRDY
    The device has not been initialized.
DSTATUS disk_status ( BYTE  pdrv)
Parameters
[in]pdrvPhysical drive number to identify the target device. Always zero at single drive system.
Return values
Thecurrent drive status is returned in combination of status flags described below. FatFs refers only STA_NOINIT and STA_PROTECT.
STA_NOINIT
Indicates that the device is not initialized. This flag is set on system reset, media removal or failure of disk_initialize() function. It is cleared on disk_initialize() function succeeded. Media change that occurs asynchronously must be captured and reflect it to the status flags, or auto-mount feature will not work correctly. If the system does not support media change detect feature, application program needs to force de-initialize the file system object with f_mount() function after the media change.
STA_NODISK
Indicates that no medium in the drive. This is always cleared on fixed disk drive. Note that FatFs does not refer this flag.
STA_PROTECT
Indicates that the medium is write protected. This is always cleared on the drives without write protect feature. Not valid if no medium in the drive.
DRESULT disk_write ( BYTE  drv,
const BYTE buff,
DWORD  sector,
UINT  count 
)

The specified memory address is not that always aligned to word boundary because the type of pointer is defined as BYTE*. For more information, refer to the description of disk_read() function.
Generally, a multiple sector transfer request must not be split into single sector transactions to the storage device, or you will never get good write throughput.
FatFs expects delayed write feature of the disk functions. The write operation to the media need not to be completed due to write operation is in progress or only stored it into the cache buffer when return from this function. But data on the buff is invalid after return from this function. The write completion request is done by CTRL_SYNC command of disk_ioctl() function. Therefore, if delayed write feature is implemented, the write throughput may be improved.
Application program MUST NOT call this function, or FAT structure on the volume can be collapsed.

Parameters
[in]pdrvPhysical drive number to identify the target device.
[in]buffPointer to the byte array to be written. The size of data to be written is sector size * count bytes.
[in]sectorStart sector number in 32-bit LBA.
[in]countNumber of sectors to write in range of from 1 to 128.
Return values
RES_OK(0)
The function succeeded.
RES_ERROR
Any hard error occured during the write operation and could not recover it.
RES_WRPRT
The medium is write protected.
RES_PARERR
Invalid parameter.
RES_NOTRDY
The device has not been initialized.
Note
This function is not needed when _FS_READONLY == 1.
FRESULT f_chdir ( const TCHAR path)

The f_chdir() function changes the current directory of the logical drive. The current directory of a drive is initialized to the root directory when the drive is auto-mounted. Note that the current directory is retained in the each file system object so that it also affects other tasks that using the volume.
Example:

1 /* Change current direcoty of the current drive (dir1 under root dir) */
2 f_chdir("/dir1");
3 /* Change current direcoty of drive 2 (parent dir) */
4 f_chdir("2:..");
Parameters
[in]pathPointer to the null-terminated string that specifies a directory to go.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_PATH
FR_INVALID_NAME
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
Note
Available when _FS_RPATH >= 1.
FRESULT f_chdrive ( const TCHAR path)

The f_chdrive() function changes the current drive. The initial value of the current drive number is 0. Note that the current drive is retained in a static variable so that it also affects other tasks that using the file functions.

Parameters
[in]pathSpecifies the logical drive number to be set as the current drive.
Return values
FR_OK
FR_INVALID_DRIVE
Note
Available when _FS_RPATH >= 1 and _VOLUMES >= 2.
FRESULT f_chmod ( const TCHAR path,
BYTE  attr,
BYTE  mask 
)

The f_chmod() function changes the attribute of a file or sub-directory.
Example:

1 /* Set read-only flag, clear archive flag and others are left unchanged. */
2 f_chmod("file.txt", AR_RDO, AR_RDO | AR_ARC);
Parameters
[in]pathPointer to the null-terminated string that specifies an object to be changed
[in]attrAttribute flags to be set in one or more combination of the following flags. The specified flags are set and others are cleard.
Attribute Description
AM_RDO Read only
AM_ARC Archive
AM_SYS System
AM_HID Hidden
[in]maskAttribute mask that specifies which attribute is changed. The specified attributes are set or cleard and others are left unchanged.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_FILE
FR_NO_PATH
FR_INVALID_NAME
FR_WRITE_PROTECTED
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
Note
Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.
FRESULT f_close ( FIL fp)

The f_close() function closes an open file object. If any data has been written to the file, the cached information of the file is written back to the volume. After the function succeeded, the file object is no longer valid and it can be discarded.
Note that if the file object is in read-only mode and _FS_LOCK option is not enabled, the file object can also be discarded without this process. However this is not recommended for future compatibility.

Parameters
[in]fpPointer to the open file object structure to be closed.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Always available.
FRESULT f_closedir ( DIR dp)

The f_closedir() function closes an open directory object. After the function succeeded, the directory object is no longer valid and it can be discarded.
Note that the directory object can also be discarded without this process if _FS_LOCK option is not enabled. However this is not recommended for future compatibility.

Parameters
[in]dpPointer to the open directory object structure to be closed.
Return values
FR_OK
FR_INT_ERR
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Available when _FS_MINIMIZE <= 1.
int f_eof ( FIL fp)

In this revision, this function is implemented as a macro.
#define f_eof(fp) ((int)((fp)->fptr == (fp)->fsize))

Parameters
[in]fpPointer to the open file object structure.
Return values
Thef_eof() function returns a non-zero value if the read/write pointer has reached end of the file; otherwise it returns a zero.
Note
Always available.
int f_error ( FIL fp)

In this revision, this function is implemented as a macro. #define f_error(fp) ((fp)->flag)

Parameters
[in]fpPointer to the open file object structure.
Return values
Returnsa non-zero value if a hard error has occured; otherwise it returns a zero.
Note
Always available.
FRESULT f_fdisk ( BYTE  pdrv,
const DWORD  part[],
void *  work 
)

The f_fdisk() function creates a partition table into the MBR of the physical drive. The partitioning rule is in generic FDISK format, so that it can create upto four primary partitions. Logical volumes in the extended partition is not supported. The part[] with four items specifies how to divide the physical drive. The first item specifies the size of first primary partition and fourth item specifies the fourth primary partition. If the value is less than or equal to 100, it specifies percentage of the partition in the entire disk space. If it is larger than 100, it specifies the partition size in unit of sector.
Example:

1 /* Volume management table defined by user (required when _MULTI_PARTITION == 1) */
2  PARTITION VolToPart[] = {
3  {0, 1}, /* Logical drive 0 ==> Physical drive 0, 1st partition */
4  {0, 2}, /* Logical drive 1 ==> Physical drive 0, 2nd partition */
5  {1, 0} /* Logical drive 2 ==> Physical drive 1, auto detection */
6  };
7 /* Initialize a brand-new disk drive mapped to physical drive 0 */
8  FATFS fs;
9  DWORD plist[] = {50, 50, 0, 0}; /* Divide drive into two partitions */
10  BYTE work[_MAX_SS];
11  f_fdisk(0, plist, work); /* Divide physical drive 0 */
12  f_mount(&fs, "0:", 0); /* Register work area to the logical drive 0 */
13  f_mkfs("0:", 0, 0); /* Create FAT volume on the logical drive 0. 2nd argument is ignored. */
14  f_mount(0, "0:", 0); /* Unregister work area from the logical drive 0 */
15  f_mount(&fs, "1:", 0); /* Register a work area to the logical drive 1 */
16  f_mkfs("1:", 0, 0); /* Create FAT volume on the logical drive 1. 2nd argument is ignored. */
17  f_mount(0, "1:", 0); /* Unregister work area from the logical drive 1 */
Parameters
[in]pdrvSpecifies the physical drive to be divided.
[in]part[]Partition map table. It must have four items.
[in]workPointer to the function work area. The size must be at least _MAX_SS bytes.
Return values
FR_OK
FR_DISK_ERR
FR_NOT_READY
FR_WRITE_PROTECTED
FR_INVALID_PARAMETER
Note
Available when _FS_READOLNY == 0, _USE_MKFS == 1 and _MULTI_PARTITION == 1.
FRESULT f_forward ( FIL fp,
UINT(*)(const BYTE *, UINT func,
UINT  btf,
UINT bf 
)

The f_forward() function reads the data from the file and forward it to the outgoing stream without data buffer. This is suitable for small memory system because it does not require any data buffer at application module. The file pointer of the file object increases in number of bytes forwarded. In case of *bf is less than btf without error, it means the requested bytes could not be transferred due to end of file or stream goes busy during data transfer.
Examples(Audio playback):

1 /*------------------------------------------------------------------------*/
2 /* Sample code of data transfer function to be called back from f_forward */
3 /*------------------------------------------------------------------------*/
4 UINT out_stream ( /* Returns number of bytes sent or stream status */
5 const BYTE *p, /* Pointer to the data block to be sent */
6 UINT btf /* >0: Transfer call (Number of bytes to be sent). 0: Sense call */
7 )
8 {
9 UINT cnt = 0;
10  if (btf == 0) { /* Sense call */
11  /* Return stream status (0: Busy, 1: Ready) */
12  /* When once it returned ready to sense call, it must accept a byte at least */
13  /* at subsequent transfer call, or f_forward will fail with FR_INT_ERR. */
14  if (FIFO_READY) cnt = 1;
15  }
16  else { /* Transfer call */
17  do { /* Repeat while there is any data to be sent and the stream is ready */
18  FIFO_PORT = *p++;
19  cnt++;
20  } while (cnt < btf && FIFO_READY);
21  }
22  return cnt;
23  }
24 /*------------------------------------------------------------------------*/
25 /* Sample code using f_forward function */
26 /*------------------------------------------------------------------------*/
27 FRESULT play_file (
28  char *fn /* Pointer to the audio file name to be played */
29 )
30 {
31 FRESULT rc;
32  FIL fil;
33  UINT dmy;
34  /* Open the audio file in read only mode */
35  rc = f_open(&fil, fn, FA_READ);
36  if (rc) return rc;
37  /* Repeat until the file pointer reaches end of the file */
38  while (rc == FR_OK && fil.fptr < fil.fsize) {
39  /* any other processes... */
40  /* Fill output stream periodicaly or on-demand */
41  rc = f_forward(&fil, out_stream, 1000, &dmy);
42  }
43  /* Close the file and return */
44  f_close(&fil);
45  return rc;
46  }
Parameters
[in]fpPointer to the open file object
[in]funcPointer to the user-defined data streaming function.
[in]btfNumber of bytes to forward in range of UINT.
[out]bfPointer to the UINT variable to return number of bytes forwarded.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Available when _USE_FORWARD == 1 and _FS_TINY == 1.
FRESULT f_getcwd ( TCHAR buff,
UINT  len 
)

The f_getcwd() function retrieves full path name of the current directory of the current drive. When _VOLUMES is larger than 1, a logical drive number is added to top of the path name.

Parameters
[out]buffPointer to the buffer to receive the current directory string.
[in]lenSize of the buffer in unit of TCHAR.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
Note
Available when _FS_RPATH == 2.
FRESULT f_getfree ( const TCHAR path,
DWORD nclst,
FATFS **  fatfs 
)

The f_getfree() function gets number of free clusters on the volume. The member csize in the file system object indicates number of sectors per cluster, so that the free space in unit of sector can be calcurated with this information. When FSINFO structure on the FAT32 volume is not in sync, this function can return an incorrect free cluster count. To avoid this problem, FatFs can be forced full FAT scan by _FS_NOFSINFO option.
Example:

1  FATFS *fs;
2 DWORD fre_clust, fre_sect, tot_sect;
3  /* Get volume information and free clusters of drive 1 */
4  res = f_getfree("1:", &fre_clust, &fs);
5  if (res) die(res);
6  /* Get total sectors and free sectors */
7  tot_sect = (fs->n_fatent - 2) * fs->csize;
8  fre_sect = fre_clust * fs->csize;
9  /* Print the free space (assuming 512 bytes/sector) */
10  printf("%10lu KiB total drive space.\n%10lu KiB available.\n",
11  tot_sect / 2, fre_sect / 2);
Parameters
[in]pathPointer to the null-terminated string that specifies the logical drive. A null-string means the default drive.
[out]nclstPointer to the DWORD variable to store number of free clusters.
[out]fatfsPointer to pointer that to store a pointer to the corresponding file system object.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
Note
Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.
FRESULT f_getlabel ( const TCHAR path,
TCHAR label,
DWORD vsn 
)
1 char str[12];
2 /* Get volume label of the default drive */
3 f_getlabel("", str, 0);
4 /* Get volume label of the drive 2 */
5 f_getlabel("2:", str, 0);
Parameters
[in]pathPointer to the null-terminated string that specifies the logical drive. Null-string specifies the default drive.
[out]labelPointer to the buffer to store the volume label. The buffer size must be at least 12 items. If the volume has no label, a null-string will be returned. Set null pointer if this information is not needed.
[out]vsnPointer to the DWORD variable to store the volume serial number. Set null pointer if this information is not needed.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
Note
Available when _USE_LABEL == 1.
TCHAR* f_gets ( TCHAR buff,
int  len,
FIL fp 
)

The f_gets() function is a wrapper function of f_read() function. The read operation continues until a '
' is stored, reached end of the file or the buffer is filled with len - 1 characters. The read string is terminated with a '\0'. When no character to read or any error occured during read operation, it returns a null pointer. The status of EOF and error can be examined with f_eof() and f_error() macros.
When FatFs is configured to Unicode API (_LFN_UNICODE == 1), data types on the srting fuctions, f_putc(), f_puts(), f_printf() and f_gets(), is also switched to Unicode. The character encoding on the file to be read/written via those functions is selected by _STRF_ENCODE option.

Parameters
[out]buffPointer to read buffer to store the read string.
[in]lenSize of the read buffer in unit of character.
[in]fpPointer to the open file object structure.
Return values
Whenthe function succeeded, buff will be returuned.
Note
Available when _USE_STRFUNC is 1 or 2. When it is set to 2, ''s contained in the file are stripped out.
FRESULT f_lseek ( FIL fp,
DWORD  ofs 
)

The f_lseek() function moves the file read/write pointer of an open file. The offset can be specified in only origin from top of the file. When an offset beyond the file size is specified at write mode, the file size is expanded to the specified offset. The file data in the expanded area is undefined because no data is written to the file. This is suitable to pre-allocate a cluster chain quickly, for fast write operation. After the f_lseek() function succeeded, the current read/write pointer should be checked in order to make sure the read/write pointer has been moved correctry. In case of the current read/write pointer is not the expected value, either of followings has been occured.

  • End of file. The specified ofs was clipped at end of the file because the file has been opened in read-only mode.
  • Disk full. There is insufficient free space on the volume to expand the file.
    Fast seek feature is enabled when _USE_FASTSEEK is set to 1 and the member cltbl in the file object is not NULL. This feature enables fast backward/long seek operations without FAT access by using CLMT (cluster link map table). The fast seek feature is also applied to f_read()/f_write() function, however, the file size cannot be expanded by f_write()/f_lseek() function.
    The CLMT must be created in the user defined DWORD array prior to use the fast seek feature. To create the CLMT, set address of the DWORD array to the member cltbl in the file object, set the array size in unit of items into the first item and call the f_lseek() function with ofs = CREATE_LINKMAP. After the function succeeded and CLMT is created, no FAT access is occured at subsequent f_read()/f_write()/f_lseek() function to the file. If the function failed with FR_NOT_ENOUGH_CORE, the given array size is insufficient for the file and number of items required is returned into the first item of the array. The required array size is (number of fragments + 1) * 2 items. For example, when the file is fragmented in 5, 12 items will be required for the CLMT.
    Examples:
    1  /* Open file */
    2  fp = malloc(sizeof (FIL));
    3  res = f_open(fp, "file.dat", FA_READ|FA_WRITE);
    4  if (res) ...
    5  /* Move to offset of 5000 from top of the file */
    6  res = f_lseek(fp, 5000);
    7  /* Move to end of the file to append data */
    8  res = f_lseek(fp, f_size(fp));
    9  /* Forward 3000 bytes */
    10  res = f_lseek(fp, f_tell(fp) + 3000);
    11  /* Rewind 2000 bytes (take care on wraparound) */
    12  res = f_lseek(fp, f_tell(fp) - 2000);
    13 
    14  /* Cluster pre-allocation (to prevent buffer overrun on streaming write) */
    15  res = f_open(fp, recfile, FA_CREATE_NEW | FA_WRITE); /* Create a file */
    16  res = f_lseek(fp, PRE_SIZE); /* Expand file size (cluster pre-allocation) */
    17  if (res || f_tell(fp) != PRE_SIZE) ... /* Check if the file has been expanded */
    18  res = f_lseek(fp, DATA_START); /* Record data stream WITHOUT cluster allocation delay */
    19  ... /* DATA_START and write block size should be aligned to sector boundary */
    20  res = f_truncate(fp); /* Truncate unused area */
    21  res = f_lseek(fp, 0); /* Put file header */
    22  ...
    23  res = f_close(fp);
    24 
    25 /* Using fast seek feature */
    26  DWORD clmt[SZ_TBL]; /* Cluster link map table buffer */
    27  res = f_lseek(fp, ofs1); /* This is normal seek (cltbl is nulled on file open) */
    28  fp->cltbl = clmt; /* Enable fast seek feature (cltbl != NULL) */
    29  clmt[0] = SZ_TBL; /* Set table size */
    30  res = f_lseek(fp, CREATE_LINKMAP); /* Create CLMT */
    31  ...
    32  res = f_lseek(fp, ofs2); /* This is fast seek */
    Parameters
    [in]fpPointer to the open file object.
    [in]ofsByte offset from top of the file.
    Return values
    FR_OK
    FR_DISK_ERR
    FR_INT_ERR
    FR_NOT_READY
    FR_INVALID_OBJECT
    FR_TIMEOUT
    Note
    Available when _FS_MINIMIZE <= 2.
FRESULT f_mkdir ( const TCHAR path)

This function creates a new directory.
Example:

1 res = f_mkdir("sub1");
2 if (res) die(res);
3 res = f_mkdir("sub1/sub2");
4 if (res) die(res);
5 res = f_mkdir("sub1/sub2/sub3");
6 if (res) die(res);
Parameters
[in]pathPointer to the null-terminated string that specifies the directory name to create.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_PATH
FR_INVALID_NAME
FR_DENIED
FR_EXIST
FR_WRITE_PROTECTED
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
Note
Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.
FRESULT f_mkfs ( const TCHAR path,
BYTE  sfd,
UINT  au 
)

The f_mkfs() function creates an FAT volume on the specified logical drive. When FDISK format is specified, a primary partition occupies entire space of the physical drive is created and then an FAT volume is created on the partition. When SFD format is specified, the FAT volume starts from the first sector of the physical drive.
If the logical drive is bound to the specific partition (1-4) by multiple partition feature (_MULTI_PARTITION), the FAT volume is created into the partition. In this case, the second argument sfd is ignored. The physical drive must have been partitioned with f_fdisk() function or any other partitioning tools prior to create the FAT volume with this function.
Note that there are two partitioning rules, FDISK and SFD. The FDISK partitioning is usually used for harddisk, MMC, SDC, CFC and U Disk. It can divide a physical drive into one or more partitions with a partition table on the MBR. However Windows does not support multiple partition on the removable disk. The SFD is non-partitioned method. The FAT volume starts from the first sector on the physical drive without partition table. It is usually used for floppy disk, Microdrive, optical disk and any type of super-floppy media.
The FAT sub-type, FAT12/FAT16/FAT32, is determined by number of clusters on the volume and nothing else, according to the FAT specification issued by Microsoft. Thus which FAT sub-type is selected, is depends on the volume size and the specified cluster size. The cluster size affects read/write throughput and space usage efficiency. Larger cluster size increases the read/write throughput and decreases the space usage efficiency of the volume.
In case of the number of clusters gets near the FAT sub-type boundaries, the function can fail with FR_MKFS_ABORTED.
Example:

1 /* Format the default drive */
2 int main (void)
3 {
4  FATFS fs; /* File system object (volume work area) */
5  FIL fil; /* File object */
6  FRESULT res; /* API result code */
7  UINT bw; /* Bytes written */
8  /* Register work area */
9  f_mount(&fs, "", 0);
10  /* Create FAT volume with default cluster size */
11  res = f_mkfs("", 0, 0);
12  if (res) ...
13  /* Create a file as new */
14  res = f_open(&fil, "hello.txt", FA_CREATE_NEW | FA_WRITE);
15  if (res) ...
16  /* Write a message */
17  f_write(&fil, "Hello, World!\r\n", 15, &bw);
18  if (bw != 15) ...
19  /* Close the file */
20  f_close(&fil);
21  /* Unregister work area */
22  f_mount(0, "", 0);
Parameters
[in]pathPointer to the null-terminated string that specifies the logical drive to be formatted. If there is no drive number, it means the default drive.
[in]sfdSpecifies partitioning rule (FDISK(0) or SFD(1)). This argument will be ignored on some case.
[in]auSpecifies size of the allocation unit (cluter) in number of bytes or sectors. When the value is from 1 to 128, it specifies number of sectors. When the value is >= _MIN_SS, it specifies number of bytes. If any invalid value, zero or not power of 2, is given, the cluster size is automatically determined depends on the volume size.
Return values
FR_OK
FR_DISK_ERR
FR_NOT_READY
FR_WRITE_PROTECTED
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_MKFS_ABORTED
FR_INVALID_PARAMETER
Note
Available when _FS_READOLNY == 0 and _USE_MKFS == 1.
FRESULT f_mount ( FATFS fs,
const TCHAR path,
BYTE  opt 
)

The f_mount() function registers/unregisters a file system object used for the logical drive to the FatFs module as follows:
1.Determines the logical drive which specified by path.
2.Clears and unregisters the regsitered work area of the drive.
3.Clears and registers the new work area to the drive if fs is not NULL.
4.Performs volume mount process to the drive if forced mount is specified.
The file system object is the work area needed for each logical drive. It must be given to the logical drive with this function prior to use any other file functions except for f_fdisk() function. To unregister a work area, specify a NULL to the fs, and then the work area can be discarded.
If forced mount is not specified, this function always succeeds regardless of the physical drive status due to delayed mount feature. It only clears (de-initializes) the given work area and registers its address to the internal table. No activity of the physical drive in this function. It can also be used to force de-initialized the registered work area of a logical drive. The volume mount processes, initialize the corresponding physical drive, find the FAT volume in it and initialize the work area, is performed in the subsequent file access functions when either or both of following condition is true.

  • File system object is not initialized. It is cleared by f_mount().
  • Physical drive is not initialized. It is de-initialized by system reset or media removal.
    If the function with forced mount failed, it means that the file system object has been registered successfully but the volume is currently not ready to use. Mount process will also be attempted in subsequent file access functions.
    If implementation of the disk I/O layer lacks media change detection, application program needs to perform a f_mount() after each media change to force cleared the file system object.
Parameters
[in]fsPointer to the new file system object to be registered. Null pointer unregisters the registered file system object.
[in]pathPointer to the null-terminated string that specifies the logical drive. The string with no drive number means the default drive.
[in]optInitialization option.
  • 0: Do not mount now (to be mounted later),
  • 1: Force mounted the volume to check if the FAT volume is available.
Return values
FR_OK
FR_INVALID_DRIVE
FR_DISK_ERR
FR_NOT_READY
FR_NO_FILESYSTEM
Note
Always available.
FRESULT f_open ( FIL fp,
const TCHAR path,
BYTE  mode 
)

After f_open() function succeeded, the file object is valid. The file object is used for subsequent read/write functions to identify the file. To close an open file, use f_close() function. If the file is modified and not closed properly, the file data will be collapsed.
If duplicated file open is needed, read here carefully. However duplicated open of a file with write mode flag is always prohibited.
Before using any file function, a work area (file system object) must be registered to the logical drive with f_mount() function. All API functions except for f_fdisk() function can work after this procedure.
Examples:

1  /* Read a text file and display it */
2 
3  FATFS FatFs; /* Work area (file system object) for logical drive */
4 
5  int main (void)
6  {
7  FIL fil; /* File object */
8  char line[82]; /* Line buffer */
9  FRESULT fr; /* FatFs return code */
10 
11 
12  /* Register work area to the default drive */
13  f_mount(&FatFs, "", 0);
14 
15  /* Open a text file */
16  fr = f_open(&fil, "message.txt", FA_READ);
17  if (fr) return (int)fr;
18 
19  /* Read all lines and display it */
20  while (f_gets(line, sizeof line, &fil))
21  printf(line);
22 
23  /* Close the file */
24  f_close(&fil);
25 
26  return 0;
27 }
1 /* Copy a file "file.bin" on the drive 1 to drive 0 */
2 
3 int main (void)
4 {
5  FATFS fs[2]; /* Work area (file system object) for logical drives */
6  FIL fsrc, fdst; /* File objects */
7  BYTE buffer[4096]; /* File copy buffer */
8  FRESULT fr; /* FatFs function common result code */
9  UINT br, bw; /* File read/write count */
10 
11 
12  /* Register work area for each logical drive */
13  f_mount(&fs[0], "0:", 0);
14  f_mount(&fs[1], "1:", 0);
15 
16  /* Open source file on the drive 1 */
17  fr = f_open(&fsrc, "1:file.bin", FA_OPEN_EXISTING | FA_READ);
18  if (fr) return (int)fr;
19 
20  /* Create destination file on the drive 0 */
21  fr = f_open(&fdst, "0:file.bin", FA_CREATE_ALWAYS | FA_WRITE);
22  if (fr) return (int)fr;
23 
24  /* Copy source to destination */
25  for (;;) {
26  fr = f_read(&fsrc, buffer, sizeof buffer, &br); /* Read a chunk of source file */
27  if (fr || br == 0) break; /* error or eof */
28  fr = f_write(&fdst, buffer, br, &bw); /* Write it to the destination file */
29  if (fr || bw < br) break; /* error or disk full */
30  }
31 
32  /* Close open files */
33  f_close(&fsrc);
34  f_close(&fdst);
35 
36  /* Unregister work area prior to discard it */
37  f_mount(NULL, "0:", 0);
38  f_mount(NULL, "1:", 0);
39 
40  return (int)fr;
41 }
Parameters
[out]fpPointer to the blank file object structure to be created.
[in]pathPointer to a null-terminated string that specifies the file name to open or create.
[in]modeMode flags that specifies the type of access and open method for the file. It is specified by a combination of following flags.
Value Description
FA_READ Specifies read access to the object. Data can be read from the file. Combine with FA_WRITE for read-write access.
FA_WRITE Specifies write access to the object. Data can be written to the file. Combine with FA_READ for read-write access.
FA_OPEN_EXISTING Opens the file. The function fails if the file is not existing. (Default) .
FA_OPEN_ALWAYS Opens the file if it is existing. If not, a new file is created. To append data to the file, use f_lseek() function after file open in this method.
FA_CREATE_NEW Creates a new file. The function fails with FR_EXIST if the file is existing.
FA_CREATE_NEW Creates a new file. If the file is existing, it will be truncated and overwritten.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_FILE
FR_NO_PATH
FR_INVALID_NAME
FR_DENIED
FR_EXIST
FR_INVALID_OBJECT
FR_WRITE_PROTECTED
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_LOCKED
FR_NOT_ENOUGH_CORE
FR_TOO_MANY_OPEN_FILES
Note
Always available. The mode flags, FA_WRITE, FA_CREATE_ALWAYS, FA_CREATE_NEW and FA_OPEN_ALWAYS, are not available when _FS_READONLY == 1.
FRESULT f_opendir ( DIR dp,
const TCHAR path 
)

The f_opendir() function opens an exsisting directory and creates a directory object for subsequent f_readdir() function.

Parameters
[out]dpPointer to the blank directory object to create a new one.
[in]pathPointer to the null-terminated string that specifies the directory name to be opened.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_PATH
FR_INVALID_NAME
FR_INVALID_OBJECT
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
FR_TOO_MANY_OPEN_FILES
Note
Available when _FS_MINIMIZE <= 1.
int f_printf ( FIL fp,
const TCHAR fmt,
  ... 
)

The f_printf() is a wrapper function of f_write(). The format control directive is a sub-set of standard library shown as follows:

  • Type: c C s S d D u U x X b B
  • Size: l L
  • Flag: 0 -
    Example:
    1 f_printf(&fil, "%d", 1234); /* "1234" */
    2 f_printf(&fil, "%6d,%3d%%", -200, 5); /* " -200, 5%" */
    3 f_printf(&fil, "%ld", 12345L); /* "12345" */
    4 f_printf(&fil, "%06d", 25); /* "000025" */
    5 f_printf(&fil, "%06d", -25); /* "000-25" */
    6 f_printf(&fil, "%-6d", 25); /* "25 " */
    7 f_printf(&fil, "%u", -1); /* "65535" or "4294967295" */
    8 f_printf(&fil, "%04x", 0xAB3); /* "0ab3" */
    9 f_printf(&fil, "%08LX", 0x123ABCL); /* "00123ABC" */
    10 f_printf(&fil, "%016b", 0x550F); /* "0101010100001111" */
    11 f_printf(&fil, "%s", "String"); /* "String" */
    12 f_printf(&fil, "%8s", "abc"); /* " abc" */
    13 f_printf(&fil, "%-8s", "abc"); /* "abc " */
    14 f_printf(&fil, "%c", 'a'); /* "a" */
    15 f_printf(&fil, "%f", 10.0); /* f_printf lacks floating point support */
    Parameters
    [in]fpPointer to the open file object structure.
    [in]fmtPointer to the null terminated format string. The terminator charactor will not be written. ... Optional arguments...
    Return values
    Whenthe function succeeded, it returns number of characters written. When the function failed due to disk full or any error, an EOF (-1) will be returned.
    Note
    Available when _FS_READONLY == 0 and _USE_STRFUNC is 1 or 2. When it is set to 2, '
    's contained in the output are converted to ''+'
    '.
    When FatFs is configured to Unicode API (_LFN_UNICODE == 1), data types on the srting fuctions, f_putc(), f_puts(), f_printf() and f_gets(), is also switched to Unicode. The character encoding on the file to be read/written via those functions is selected by _STRF_ENCODE option.
int f_putc ( TCHAR  chr,
FIL fp 
)

The f_putc() function is a wrapper function of f_write() function.

Parameters
[in]chrA character to be put.
[in]fpPointer to the open file object structuer.
Return values
Whenthe character was written successfuly, it returns number of characters written. When the function failed due to disk full or any error, an EOF (-1) will be returned.
When FatFs is configured to Unicode API (_LFN_UNICODE == 1), character encoding on the string fuctions, f_putc(), f_puts(), f_printf() and f_gets(), is also switched to Unicode. The character encoding on the file to be read/written via those functions is selected by _STRF_ENCODE option.
Note
Available when _FS_READONLY == 0 and _USE_STRFUNC is 1 or 2. When it is set to 2, a '
' is converted to ''+'
'.
int f_puts ( const TCHAR str,
FIL fp 
)

The f_puts() function is a wrapper function of f_write() function.

Parameters
[in]strPointer to the null terminated string to be written. The terminator character will not be written.
[in]fpPointer to the open file object structure.
Return values
Whenthe function succeeded, it returns number of characters written. When the write operation is aborted due to disk full or any error, an EOF (-1) will be returned.
When FatFs is configured to Unicode API (_LFN_UNICODE == 1), character encoding on the srting fuctions, f_putc(), f_puts(), f_printf() and f_gets(), is also switched to Unicode. The character encoding on the file to be read/written via those functions is selected by _STRF_ENCODE option.
Note
Available when _FS_READONLY == 0 and _USE_STRFUNC is 1 or 2. When it is set to 2, '
's contained in the string are converted to ''+'
'.
FRESULT f_read ( FIL fp,
void *  buff,
UINT  btr,
UINT br 
)

The file read/write pointer of the file object advances number of bytes read. After the function succeeded, *br should be checked to detect end of the file. In case of *br is less than btr, it means the read/write pointer reached end of the file during read operation.

Parameters
[in]fpPointer to the open file object.
[out]buffPointer to the buffer to store read data.
[in]btrNumber of bytes to read in range of UINT type.
[out]brPointer to the UINT variable to return number of bytes read. The value is always valid after the function call regardless of the result.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Always available.
FRESULT f_readdir ( DIR dp,
FILINFO fno 
)

The f_readdir() function reads directory items, file and directory, in sequence. All items in the directory can be read by calling f_readdir() function repeatedly. When relative path feature is enabled (_FS_RPATH >= 1), dot entries ("." and "..") are not filtered out and they will appear in the read items. When all directory items have been read and no item to read, a null string is returned into the fname[] without any error. When a null pointer is given to the fno, the read index of the directory object is rewinded.
When LFN feature is enabled, lfname and lfsize in the file information structure must be initialized with valid value prior to use it. The lfname is a pointer to the LFN read buffer. The lfsize is size of the LFN read buffer in unit of TCHAR. If the LFN is not needed, set a null pointer to the lfname and the LFN is not returned. A null string will be returned into the LFN read buffer in case of following conditions.

  • The directory item has no LFN information.
  • Either the size of read buffer or LFN working buffer is insufficient for the LFN.
  • The LFN contains any Unicode character that cannot be converted to OEM code. (not the case at Unicode API cfg.)
    When the directory item has no LFN information, lower case characters can be contained in the fname[].
    Sample Code:
    1  FRESULT scan_files (
    2  char* path /* Start node to be scanned (also used as work area) */
    3 )
    4 
    5 {
    6  FRESULT res;
    7  FILINFO fno;
    8  DIR dir;
    9  int i;
    10  char *fn; /* This function assumes non-Unicode configuration */
    11  #if _USE_LFN
    12  static char lfn[_MAX_LFN + 1]; /* Buffer to store the LFN */
    13  fno.lfname = lfn;
    14  fno.lfsize = sizeof lfn;
    15  #endif
    16  res = f_opendir(&dir, path); /* Open the directory */
    17  if (res == FR_OK) {
    18  i = strlen(path);
    19  for (;;) {
    20  res = f_readdir(&dir, &fno); /* Read a directory item */
    21  if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */
    22  if (fno.fname[0] == '.') continue; /* Ignore dot entry */
    23  #if _USE_LFN
    24  fn = *fno.lfname ? fno.lfname : fno.fname;
    25  #else
    26  fn = fno.fname;
    27  #endif
    28  if (fno.fattrib & AM_DIR) { /* It is a directory */
    29  sprintf(&path[i], "/%s", fn);
    30  res = scan_files(path);
    31  path[i] = 0;
    32  if (res != FR_OK) break;
    33  } else { /* It is a file. */
    34  printf("%s/%s\n", path, fn);
    35  }
    36  }
    37  f_closedir(&dir)
    38  }
    39  return res;
    40 }
    Parameters
    [in]dpPointer to the open directory object.
    [out]fnoPointer to the file information structure to store the read item.
    Return values
    FR_OK
    FR_DISK_ERR
    FR_INT_ERR
    FR_NOT_READY
    FR_INVALID_OBJECT
    FR_TIMEOUT
    FR_NOT_ENOUGH_CORE
    Note
    Available when _FS_MINIMIZE <= 1.
FRESULT f_rename ( const TCHAR old_name,
const TCHAR new_name 
)

Renames a file or sub-directory and can also move it to other directory within the same logical drive. Do not rename open objects or directry table can be broken.
Example:

1 /* Rename an object */
2 f_rename("oldname.txt", "newname.txt");
3 
4 /* Rename and move an object to other directory */
5 f_rename("oldname.txt", "dir1/newname.txt");
Parameters
[in]old_namePointer to a null-terminated string that specifies an existing file or sub-directory to be renamed.
[in]new_namePointer to a null-terminated string that specifies the new object name. The drive number specified in this string is ignored and one determined by old_name is used instead.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_FILE
FR_NO_PATH
FR_INVALID_NAME
FR_DENIED
FR_EXIST
FR_EXIST
FR_WRITE_PROTECTED
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_LOCKED
FR_NOT_ENOUGH_CORE
Note
Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.

+ Here is the caller graph for this function:

FRESULT f_setlabel ( const TCHAR label)

When the string has a drive number, the volume label will be set to the volume specified by the drive number. If not, the label will be set to the default drive. If the given string is a null-string, the volume label on the volume will be removed. The format of the volume label is similar to the short file name but there are some differences shown below:

  • 11 bytes or less in length as local character code. LFN extention is not applied to the volume label.
  • Cannot contain period.
  • Can contain spaces anywhere in the volume label. Trailing spaces are truncated off.
    Example:
    1 /* Set volume label to the default drive */
    2 f_setlabel("DATA DISK");
    3 /* Set volume label to the drive 2 */
    4 f_setlabel("2:DISK 3 OF 4");
    5 /* Remove volume label of the drive 2 */
    6 f_setlabel("2:");
    Parameters
    [in]labelPointer to the null-terminated string that specifies the logical drive. Null-string specifies the default drive.
    Return values
    FR_OK
    FR_DISK_ERR
    FR_INT_ERR
    FR_NOT_READY
    FR_INVALID_NAME
    FR_WRITE_PROTECTED
    FR_INVALID_DRIVE
    FR_NOT_ENABLED
    FR_NO_FILESYSTEM
    FR_TIMEOUT
    Note
    Available when _FS_READONLY == 0 and _USE_LABEL == 1.
DWORD f_size ( FIL fp)

In this revision, the f_size() function is implemented as a macro.
#define f_size(fp) ((fp)->fsize)

Parameters
[in]fpPointer to the open file object structure.
Return values
Returnsthe size of the file in unit of byte.
Note
Always available.
FRESULT f_stat ( const TCHAR path,
FILINFO fno 
)

The f_stat() function checks the existence of a file or sub-directory. If not exist, the function returns with FR_NO_FILE. If exist, the function returns with FR_OK and the informations of the object, file size, timestamp, attribute and SFN, are stored to the file information structure. For details of the file information, refer to the FILINFO structure and f_readdir() function.
When LFN feature is enabled, lfname in the file information structure must be NULLed prior to use it.
Examples:

1 FRESULT fr;
2 FILINFO fno;
3 printf("Test for 'file.txt'...\n");
4 #if _USE_LFN
5 fno.lfname = 0;
6 #endif
7 fr = f_stat("file.txt", &fno);
8 switch (fr) {
9 case FR_OK:
10  printf("Size: %u\n", fno.fsize);
11  printf("Timestamp: %u/%02u/%02u, %02u:%02u\n",
12  (fno.fdate >> 9) + 1980, fno.fdate >> 5 & 15, fno.fdate & 31,
13  fno.ftime >> 11, fno.ftime >> 5 & 63);
14  printf("Attributes: %c%c%c%c%c\n",
15  (fno.fattrib & AM_DIR) ? 'D' : '-',
16  (fno.fattrib & AM_RDO) ? 'R' : '-',
17  (fno.fattrib & AM_HID) ? 'H' : '-',
18  (fno.fattrib & AM_SYS) ? 'S' : '-',
19  (fno.fattrib & AM_ARC) ? 'A' : '-');
20  break;
21  case FR_NO_FILE:
22  printf("It is not exist.\n");
23  break;
24  default:
25  printf("An error occured. (%d)\n", fr);
26  }
Parameters
[in]pathPointer to the null-terminated string that specifies the object to get its information.
[out]fnoPointer to the blank FILINFO structure to store the information of the object. Set null pointer if it is not needed.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_FILE
FR_NO_PATH
FR_INVALID_NAME
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
Note
Available when _FS_MINIMIZE == 0.

+ Here is the caller graph for this function:

FRESULT f_sync ( FIL fp)

The f_sync() function performs the same process as f_close() function but the file is left opened and can continue read/write/seek operations to the file. This is suitable for the applications that open files for a long time in write mode, such as data logger. Performing f_sync() function of periodic or immediataly after f_write() function can minimize the risk of data loss due to a sudden blackout or an unintentional media removal.
However there is no sense in f_sync() function immediataly before f_close() function because it performs f_sync() function in it. In other words, the differnce between those functions is that the file object is invalidated or not.

Parameters
[in]fpPointer to the open file object to be flushed.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Available when _FS_READONLY == 0.
DWORD f_tell ( FIL fp)

In this revision, the f_tell() function is implemented as a macro.
#define f_tell(fp) ((fp)->fptr)

Parameters
[in]fpPointer to the open file object structure.
Return values
Returnscurrent read/write pointer of the file.
Note
Always available.
FRESULT f_truncate ( FIL fp)

The f_truncate() function truncates the file size to the current file read/write pointer. This function has no effect if the file read/write pointer is already pointing end of the file.

Parameters
[in]fpPointer to the open file object to be truncated.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.
FRESULT f_unlink ( const TCHAR path)

If condition of the object to be removed is applicable to the following terms, the function will be rejected.

  • The file/sub-directory must not have read-only attribute (AM_RDO), or the function will be rejected with FR_DENIED.
  • The sub-directory must be empty and must not be current directory, or the function will be rejected with FR_DENIED.
  • The file/sub-directory must not be opened, or the FAT volume can be collapsed. It can be rejected with FR_LOCKED when file lock feature is enabled.
    Parameters
    [in]pathPointer to the null-terminated string that specifies an object to be removed.
    Return values
    FR_OK
    FR_DISK_ERR
    FR_INT_ERR
    FR_NOT_READY
    FR_NO_FILE
    FR_NO_PATH
    FR_INVALID_NAME
    FR_DENIED
    FR_EXIST
    FR_WRITE_PROTECTED
    FR_INVALID_DRIVE
    FR_NOT_ENABLED
    FR_NO_FILESYSTEM
    FR_TIMEOUT
    FR_LOCKED
    FR_NOT_ENOUGH_CORE
    Note
    Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.

+ Here is the caller graph for this function:

FRESULT f_utime ( const TCHAR path,
const FILINFO fno 
)

The f_utime() function changes the timestamp of a file or sub-directory
Example:

1 FRESULT set_timestamp (
2  char *obj, /* Pointer to the file name */
3  int year,
4  int month,
5  int mday,
6  int hour,
7  int min,
8  int sec
9 )
10 {
11  FILINFO fno;
12  fno.fdate = (WORD)(((year - 1980) * 512U) | month * 32U | mday);
13  fno.ftime = (WORD)(hour * 2048U | min * 32U | sec / 2U);
14  return f_utime(obj, &fno);
15 }
Parameters
[in]pathPointer to the null-terminated string that specifies an object to be changed.
[in]fnoPointer to the file information structure that has a timestamp to be set in member fdate and ftime. Do not care any other members.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_NO_FILE
FR_NO_PATH
FR_INVALID_NAME
FR_WRITE_PROTECTED
FR_INVALID_DRIVE
FR_NOT_ENABLED
FR_NO_FILESYSTEM
FR_TIMEOUT
FR_NOT_ENOUGH_CORE
Note
Available when _FS_READONLY == 0 and _FS_MINIMIZE == 0.
FRESULT f_write ( FIL fp,
const void *  buff,
UINT  btw,
UINT bw 
)

The read/write pointer of the file object advances number of bytes written. After the function succeeded, *bw should be checked to detect the disk full. In case of *bw is less than btw, it means the volume got full during the write operation. The function can take a time when the volume is full or close to full.

Parameters
[in]fpPointer to the open file object.
[in]buffPointer to the data to be written.
[in]btwSpecifies number of bytes to write in range of UINT type.
[out]bwPointer to the UINT variable to return the number of bytes written. The value is always valid after the function call regardless of the result.
Return values
FR_OK
FR_DISK_ERR
FR_INT_ERR
FR_NOT_READY
FR_INVALID_OBJECT
FR_TIMEOUT
Note
Available when _FS_READONLY == 0.
DWORD get_fattime ( void  )

The get_fattime() function shall return any valid time even if the system does not support a real time clock. If a zero is returned, the file will not have a valid timestamp.

Parameters
[in]pdrvPhysical drive number to identify the target device.
[in]buffPointer to the byte array to be written. The size of data to be written is sector size * count bytes.
[in]sectorStart sector number in 32-bit LBA.
[in]countNumber of sectors to write in range of from 1 to 128.
Return values
Currnettime is returned with packed into a DWORD value. The bit field is as follows:
bit31:25
Year origin from the 1980 (0..127)
bit24:21
Month (1..12)
bit20:16
Day of the month(1..31)
bit15:11
Hour (0..23)
bit10:5
Minute (0..59)
bit4:0
Second / 2 (0..29)
Note
This function is not needed when _FS_READONLY == 1.

All rights reserved. The use is subject to the XDK SDK EULA by Bosch Connected Devices and Solutions GmbH.
This documentation file has been automatically generated on Thu Mar 14 2019 19:12:49 by doxygen 1.8.8