📄 tff.c
字号:
/*-----------------------------------------------------------------------*/
#if _FS_READONLY == 0
static
BYTE* reserve_direntry ( /* !=NULL: successful, NULL: failed */
DIR *dirobj /* Target directory to create new entry */
)
{
CLUST clust;
DWORD sector;
BYTE c, n, *dptr;
FATFS *fs = FatFs;
/* Re-initialize directory object */
clust = dirobj->sclust;
if (clust) { /* Dyanmic directory table */
dirobj->clust = clust;
dirobj->sect = clust2sect(clust);
} else { /* Static directory table */
dirobj->sect = fs->dirbase;
}
dirobj->index = 0;
do {
if (!move_window(dirobj->sect)) return NULL;
dptr = &fs->win[(dirobj->index & 15) * 32]; /* Pointer to the directory entry */
c = *dptr;
if (c == 0 || c == 0xE5) return dptr; /* Found an empty entry! */
} while (next_dir_entry(dirobj)); /* Next directory pointer */
/* Reached to end of the directory table */
/* Abort when static table or could not stretch dynamic table */
if (!clust || !(clust = create_chain(dirobj->clust))) return NULL;
if (!move_window(0)) return 0;
fs->winsect = sector = clust2sect(clust); /* Cleanup the expanded table */
memset(fs->win, 0, 512);
for (n = fs->sects_clust; n; n--) {
if (disk_write(0, fs->win, sector, 1) != RES_OK) return NULL;
sector++;
}
fs->winflag = 1;
return fs->win;
}
#endif /* _FS_READONLY */
/*-----------------------------------------------------------------------*/
/* Load boot record and check if it is a FAT boot record */
/*-----------------------------------------------------------------------*/
static
BYTE check_fs ( /* 0:Not a boot record, 1:Valid boot record but not a FAT, 2:FAT boot record */
DWORD sect /* Sector# to check if it is a FAT boot record or not */
)
{
FATFS *fs = FatFs;
if (disk_read(0, fs->win, sect, 1) != RES_OK) /* Load boot record */
return 0;
if (LD_WORD(&fs->win[510]) != 0xAA55) /* Check record signature */
return 0;
if (!memcmp(&fs->win[54], "FAT", 3)) /* Check FAT signature */
return 2;
#if _FAT32 != 0
if (!memcmp(&fs->win[82], "FAT32", 5) && !(fs->win[40] & 0x80))
return 2;
#endif
return 1;
}
/*-----------------------------------------------------------------------*/
/* Make sure that the file system is valid */
/*-----------------------------------------------------------------------*/
static
FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */
const char **path, /* Pointer to pointer to the path name (drive number) */
BYTE chk_wp /* !=0: Check media write protection for wrinting fuctions */
)
{
BYTE fmt;
DSTATUS stat;
DWORD basesect, fatsize, totalsect, maxclust;
const char *p = *path;
FATFS *fs = FatFs;
while (*p == ' ') p++; /* Strip leading spaces */
if (*p == '/') p++; /* Strip heading slash */
*path = p; /* Return pointer to the path name */
/* Is the file system object registered? */
if (!fs) return FR_NOT_ENABLED;
/* Chekck if the logical drive has been mounted or not */
if (fs->fs_type) {
stat = disk_status(0);
if (!(stat & STA_NOINIT)) { /* If the physical drive is kept initialized */
#if _FS_READONLY == 0
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
return FR_WRITE_PROTECTED;
#endif
return FR_OK; /* The file system object is valid */
}
}
/* The logical drive has not been mounted, following code attempts to mount the logical drive */
memset(fs, 0, sizeof(FATFS)); /* Clean-up the file system object */
stat = disk_initialize(0); /* Initialize low level disk I/O layer */
if (stat & STA_NOINIT) /* Check if the drive is ready */
return FR_NOT_READY;
#if _FS_READONLY == 0
if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
return FR_WRITE_PROTECTED;
#endif
/* Search FAT partition on the drive */
fmt = check_fs(basesect = 0); /* Check sector 0 as an SFD format */
if (fmt == 1) { /* Not a FAT boot record, it may be patitioned */
/* Check a partition listed in top of the partition table */
if (fs->win[0x1C2]) { /* Is the 1st partition existing? */
basesect = LD_DWORD(&fs->win[0x1C6]); /* Partition offset in LBA */
fmt = check_fs(basesect); /* Check the partition */
}
}
if (fmt != 2 || fs->win[12] != 2) /* No valid FAT patition is found */
return FR_NO_FILESYSTEM;
/* Initialize the file system object */
fatsize = LD_WORD(&fs->win[22]); /* Number of sectors per FAT */
if (!fatsize) fatsize = LD_DWORD(&fs->win[36]);
fs->sects_fat = (CLUST)fatsize;
fs->n_fats = fs->win[16]; /* Number of FAT copies */
fatsize *= fs->n_fats; /* Number of sectors in FAT area */
fs->fatbase = basesect += LD_WORD(&fs->win[14]); /* FAT start sector (lba) */
basesect += fatsize; /* Next sector of FAT area (lba) */
fs->sects_clust = fs->win[13]; /* Number of sectors per cluster */
fs->n_rootdir = LD_WORD(&fs->win[17]); /* Nmuber of root directory entries */
totalsect = LD_WORD(&fs->win[19]); /* Number of sectors on the file system */
if (!totalsect) totalsect = LD_DWORD(&fs->win[32]);
fs->max_clust = maxclust = (totalsect /* Last cluster# + 1 */
- LD_WORD(&fs->win[14]) - fatsize - fs->n_rootdir / 16
) / fs->sects_clust + 2;
fmt = FS_FAT12; /* Determins the FAT type */
if (maxclust >= 0xFF7) fmt = FS_FAT16;
#if _FAT32 == 0
if (maxclust >= 0xFFF7) return FR_NO_FILESYSTEM;
#else
if (maxclust >= 0xFFF7) fmt = FS_FAT32;
if (fmt == FS_FAT32)
fs->dirbase = LD_DWORD(&fs->win[44]); /* Root directory start cluster */
else
#endif
fs->dirbase = basesect; /* Root directory start sector (lba) */
fs->database = basesect + fs->n_rootdir / 16; /* Data start sector (lba) */
fs->fs_type = fmt; /* FAT type */
fs->id = ++fsid; /* File system mount ID */
return FR_OK;
}
/*-----------------------------------------------------------------------*/
/* Check if the file/dir object is valid or not */
/*-----------------------------------------------------------------------*/
static
FRESULT validate ( /* FR_OK(0): The id is valid, !=0: Not valid */
const FATFS *fs, /* Pointer to the file system object */
WORD id /* id member of the target object to be checked */
)
{
if (!fs || (WORD)~fs->id != id)
return FR_INVALID_OBJECT;
if (disk_status(0) & STA_NOINIT)
return FR_NOT_READY;
return FR_OK;
}
/*--------------------------------------------------------------------------
Public Functions
--------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------*/
/* Mount/Unmount a Locical Drive */
/*-----------------------------------------------------------------------*/
FRESULT f_mount (
BYTE drv, /* Logical drive number to be mounted/unmounted */
FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
)
{
FATFS *fsobj;
if (drv) return FR_INVALID_DRIVE;
fsobj = FatFs;
FatFs = fs;
if (fsobj) memset(fsobj, 0, sizeof(FATFS));
if (fs) memset(fs, 0, sizeof(FATFS));
return FR_OK;
}
/*-----------------------------------------------------------------------*/
/* Open or Create a File */
/*-----------------------------------------------------------------------*/
FRESULT f_open (
FIL *fp, /* Pointer to the blank file object */
const char *path, /* Pointer to the file name */
BYTE mode /* Access mode and file open mode flags */
)
{
FRESULT res;
BYTE *dir;
DIR dirobj;
char fn[8+3+1];
FATFS *fs = FatFs;
#if _FS_READONLY == 0
res = auto_mount(&path, mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS));
#else
res = auto_mount(&path, 0);
#endif
if (res != FR_OK) return res;
/* Trace the file path */
res = trace_path(&dirobj, fn, path, &dir); /* Trace the file path */
#if _FS_READONLY == 0
/* Create or Open a File */
if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS)) {
CLUST ps, rs;
DWORD tm;
if (res != FR_OK) { /* No file, create new */
mode |= FA_CREATE_ALWAYS;
if (res != FR_NO_FILE) return res;
dir = reserve_direntry(&dirobj); /* Reserve a directory entry */
if (dir == NULL) return FR_DENIED;
memset(dir, 0, 32); /* Initialize the new entry */
memcpy(dir, fn, 8+3);
*(dir+12) = fn[11];
} else { /* Any object is already existing */
if (dir == NULL || (*(dir+11) & (AM_RDO|AM_DIR))) /* Could not overwrite (R/O or DIR) */
return FR_DENIED;
if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero */
#if _FAT32 != 0
rs = ((DWORD)LD_WORD(dir+20) << 16) | LD_WORD(dir+26);
ST_WORD(dir+20, 0);
#else
rs = LD_WORD(dir+26);
#endif
ST_WORD(dir+26, 0); /* cluster = 0 */
ST_DWORD(dir+28, 0); /* size = 0 */
fs->winflag = 1;
ps = fs->winsect; /* Remove the cluster chain */
if (!remove_chain(rs) || !move_window(ps))
return FR_RW_ERROR;
}
}
if (mode & FA_CREATE_ALWAYS) {
*(dir+11) = AM_ARC;
tm = get_fattime();
ST_DWORD(dir+14, tm); /* Created time */
ST_DWORD(dir+22, tm); /* Updated time */
fs->winflag = 1;
}
}
/* Open a File */
else {
#endif /* _FS_READONLY */
if (res != FR_OK) return res; /* Trace failed */
if (dir == NULL || (*(dir+11) & AM_DIR)) /* It is a directory */
return FR_NO_FILE;
#if _FS_READONLY == 0
if ((mode & FA_WRITE) && (*(dir+11) & AM_RDO)) /* R/O violation */
return FR_DENIED;
}
#endif
#if _FS_READONLY == 0
fp->flag = mode & (FA_WRITE|FA_READ);
fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
fp->dir_ptr = dir;
#else
fp->flag = mode & FA_READ;
#endif
fp->org_clust = LD_WORD(dir+26); /* File start cluster */
fp->fsize = LD_DWORD(dir+28); /* File size */
fp->fptr = 0; /* File ptr */
fp->sect_clust = 1; /* Sector counter */
fp->fs = fs; fp->id = ~fs->id; /* Owner file system object of the file */
return FR_OK;
}
/*-----------------------------------------------------------------------*/
/* Read File */
/*-----------------------------------------------------------------------*/
FRESULT f_read (
FIL *fp, /* Pointer to the file object */
void *buff, /* Pointer to data buffer */
WORD btr, /* Number of bytes to read */
WORD *br /* Pointer to number of bytes read */
)
{
DWORD sect, remain;
WORD rcnt;
CLUST clust;
BYTE cc, *rbuff = buff;
FRESULT res;
FATFS *fs = fp->fs;
*br = 0;
res = validate(fs, fp->id);
if (res) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */
remain = fp->fsize - fp->fptr;
if (btr > remain) btr = (WORD)remain; /* Truncate read count by number of bytes left */
for ( ; btr; /* Repeat until all data transferred */
rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
if ((fp->fptr % 512) == 0) { /* On the sector boundary */
if (--(fp->sect_clust)) { /* Decrement left sector counter */
sect = fp->curr_sect + 1; /* Get current sector */
} else { /* On the cluster boundary, get next cluster */
clust = (fp->fptr == 0) ?
fp->org_clust : get_cluster(fp->curr_clust);
if (clust < 2 || clust >= fs->max_clust)
goto fr_error;
fp->curr_clust = clust; /* Current cluster */
sect = clust2sect(clust); /* Get current sector */
fp->sect_clust = fs->sects_clust; /* Re-initialize the left sector counter */
}
fp->curr_sect = sect; /* Update current sector */
cc = btr / 512; /* When left bytes >= 512, */
if (cc) { /* Read maximum contiguous sectors directly */
if (cc > fp->sect_clust) cc = fp->sect_clust;
if (disk_read(0, rbuff, sect, cc) != RES_OK)
goto fr_error;
fp->sect_clust -= cc - 1;
fp->curr_sect += cc - 1;
rcnt = cc * 512; continue;
}
}
if (!move_window(fp->curr_sect)) goto fr_error; /* Move sector window */
rcnt = 512 - (WORD)(fp->fptr % 512); /* Copy fractional bytes from sector window */
if (rcnt > btr) rcnt = btr;
memcpy(rbuff, &fs->win[fp->fptr % 512], rcnt);
}
return FR_OK;
fr_error: /* Abort this function due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
/*-----------------------------------------------------------------------*/
/* Write File */
/*-----------------------------------------------------------------------*/
#if _FS_READONLY == 0
FRESULT f_write (
FIL *fp, /* Pointer to the file object */
const void *buff, /* Pointer to the data to be written */
WORD btw, /* Number of bytes to write */
WORD *bw /* Pointer to number of bytes written */
)
{
DWORD sect;
WORD wcnt;
CLUST clust;
BYTE cc;
FRESULT res;
const BYTE *wbuff = buff;
FATFS *fs = fp->fs;
*bw = 0;
res = validate(fs, fp->id);
if (res) return res;
if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
if (fp->fsize + btw < fp->fsize) btw = 0; /* File size cannot reach 4GB */
for ( ; btw; /* Repeat until all data transferred */
wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
if ((fp->fptr % 512) == 0) { /* On the sector boundary */
if (--(fp->sect_clust)) { /* Decrement left sector counter */
sect = fp->curr_sect + 1; /* Get current sector */
} else { /* On the cluster boundary, get next cluster */
if (fp->fptr == 0) { /* Is top of the file */
clust = fp->org_clust;
if (clust == 0) /* No cluster is created yet */
fp->org_clust = clust = create_chain(0); /* Create a new cluster chain */
} else { /* Middle or end of file */
clust = create_chain(fp->curr_clust); /* Trace or streach cluster chain */
}
if (clust < 2 || clust >= fs->max_clust) break;
fp->curr_clust = clust; /* Current cluster */
sect = clust2sect(clust); /* Get current sector */
fp->sect_clust = fs->sects_clust; /* Re-initialize the left sector counter */
}
fp->curr_sect = sect; /* Update current sector */
cc = btw / 512; /* When left bytes >= 512, */
if (cc) { /* Write maximum contiguous sectors directly */
if (cc > fp->sect_clust) cc = fp->sect_clust;
if (disk_write(0, wbuff, sect, cc) != RES_OK)
goto fw_error;
fp->sect_clust -= cc - 1;
fp->curr_sect += cc - 1;
wcnt = cc * 512; continue;
}
if (fp->fptr >= fp->fsize) { /* Flush R/W window if needed */
if (!move_window(0)) goto fw_error;
fs->winsect = fp->curr_sect;
}
}
if (!move_window(fp->curr_sect)) /* Move sector window */
goto fw_error;
wcnt = 512 - (WORD)(fp->fptr % 512); /* Copy fractional bytes bytes to sector window */
if (wcnt > btw) wcnt = btw;
memcpy(&fs->win[fp->fptr % 512], wbuff, wcnt);
fs->winflag = 1;
}
if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
fp->flag |= FA__WRITTEN; /* Set file changed flag */
return FR_OK;
fw_error: /* Abort this function due to an unrecoverable error */
fp->flag |= FA__ERROR;
return FR_RW_ERROR;
}
#endif /* _FS_READONLY */
/*-----------------------------------------------------------------------*/
/* Seek File Pointer */
/*-----------------------------------------------------------------------*/
FRESULT f_lseek (
FIL *fp, /* Pointer to the file object */
DWORD ofs /* File pointer from top of file */
)
{
CLUST clust;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -