⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fat.c

📁 SD卡FAT文件系统
💻 C
📖 第 1 页 / 共 3 页
字号:
}





/*--------------------------------------------------------------------------*/
/* Public Funciotns                                                         */
/*--------------------------------------------------------------------------*/


/*----------------------------------------------------------*/
/* Load File System Information and Initialize FatFs Module */

uint16 f_mountdrv (void)
{
	uint8 fat;
	uint32 sect, fatend, maxsect;
	FATFS *fs = FatFs;


	if (!fs) return FR_NOT_ENABLED;

	/* Initialize file system object */
	memset(fs, 0, sizeof(FATFS));

	/* Initialize disk drive */
	if (disk_initialize() & STA_NOINIT)	return FR_NOT_READY;

	/* Search FAT partition */
	fat = check_fs(sect = 0);		/* Check sector 0 as an SFD format */
	if (!fat) {						/* Not a FAT boot record, it will be an FDISK format */
		/* Check a partition listed in top of the partition table */
		if (fs->win[0x1C2]) {					/* Is the partition existing? */
			sect = LDF_DWORD(&(fs->win[0x1C6]));	/* Partition offset in LBA */
			fat = check_fs(sect);				/* Check the partition */
		}
	}
	if (!fat) return FR_NO_FILESYSTEM;	/* No FAT patition */

	/* Initialize file system object */
	fs->fs_type = fat;								/* FAT type */
	fs->sects_fat = 								/* Sectors per FAT */
		(fat == FS_FAT32) ? LDF_DWORD(&(fs->win[0x24])) : LDF_WORD(&(fs->win[0x16]));
	fs->sects_clust = fs->win[0x0D];				/* Sectors per cluster */
	fs->n_fats = fs->win[0x10];						/* Number of FAT copies */
	fs->fatbase = sect + LDF_WORD(&(fs->win[0x0E]));	/* FAT start sector (physical) */
	fs->n_rootdir = LDF_WORD(&(fs->win[0x11]));		/* Nmuber of root directory entries */

	fatend = fs->sects_fat * fs->n_fats + fs->fatbase;
	if (fat == FS_FAT32) {
		fs->dirbase = LDF_DWORD(&(fs->win[0x2C]));	/* FAT32: Directory start cluster */
		fs->database = fatend;	 					/* FAT32: Data start sector (physical) */
	} else {
		fs->dirbase = fatend;						/* Directory start sector (physical) */
		fs->database = fs->n_rootdir / 16 + fatend;	/* Data start sector (physical) */
	}
	maxsect = LDF_DWORD(&(fs->win[0x20]));			/* Calculate maximum cluster number */
	if (!maxsect) maxsect = LDF_WORD(&(fs->win[0x13]));
	fs->max_clust = (maxsect - fs->database + sect) / fs->sects_clust + 2;

	return FR_OK;
}



/*-----------------------*/
/* Open or Create a File */

uint16 f_open (
	FIL *fp,			/* Pointer to the buffer of new file object to create */
	const sint8 *path,	/* Pointer to the file name */
	uint8 mode			/* Access mode and file open mode flags */
)
{
	uint16 res;
	uint8 *dir;
	DIR dirscan;
	sint8 fn[8+3+1];
	FATFS *fs = FatFs;


	if ((res = check_mounted()) != FR_OK) return res;
	if ((mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS)) && (disk_status() & STA_PROTECT))
		return FR_WRITE_PROTECTED;

	res = trace_path(&dirscan, fn, path, &dir);	/* Trace the file path */

	/* Create or Open a File */
	if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS)) {
		uint32 dw;
		if (res != FR_OK) {		/* No file, create new */
			mode |= FA_CREATE_ALWAYS;
			if (res != FR_NO_FILE) return res;
			dir = reserve_direntry(&dirscan);	/* Reserve a directory entry */
			if (dir == NULL) return FR_DENIED;
			memcpy(dir, fn, 8+3);		/* Initialize the new entry */
			*(dir+12) = fn[11];
			memset(dir+13, 0, 32-13);
		} 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 */
				dw = fs->winsect;			/* Remove the cluster chain */
				if (!remove_chain(((uint32)LDF_WORD(dir+20) << 16) | LDF_WORD(dir+26))
					|| !move_window(dw) )
					return FR_RW_ERROR;
				ST_WORD(dir+20, 0); ST_WORD(dir+26, 0);	/* cluster = 0 */
				ST_DWORD(dir+28, 0);					/* size = 0 */
			}
		}
		if (mode & FA_CREATE_ALWAYS) {
			*(dir+11) = AM_ARC;
			dw = get_fattime();
			ST_DWORD(dir+14, dw);	/* Created time */
			ST_DWORD(dir+22, dw);	/* Updated time */
			fs->winflag = 1;
		}
	}
	/* Open a File */
	else {
		if (res != FR_OK) return res;		/* Trace failed */
		if ((dir == NULL) || (*(dir+11) & AM_DIR))	/* It is a directory */
			return FR_NO_FILE;
		if ((mode & FA_WRITE) && (*(dir+11) & AM_RDO)) /* R/O violation */
			return FR_DENIED;
	}

	fp->flag       = mode & (FA_WRITE|FA_READ);
	fp->dir_sect   = fs->winsect;			/* Pointer to the directory entry */
	fp->dir_ptr    = dir;
	fp->org_clust  = ((uint32)LDF_WORD(dir+20) << 16) | LDF_WORD(dir+26);	/* File start cluster */
	fp->fsize      = LDF_DWORD(dir+28);		/* File size */
	fp->fptr       = 0;						/* File ptr */
	fp->sect_clust = 1;					/* Sector counter */
	fs->files++;
	return FR_OK;
}



/*-----------*/
/* Read File */

uint16 f_read (
	FIL *fp, 		/* Pointer to the file object */
	void *buff,		/* Pointer to data buffer */
	uint16 btr,		/* Number of bytes to read */
	uint16 *br		/* Pointer to number of bytes read */
)
{
	uint32 clust, sect, ln;
	uint16 rcnt;
	uint8 cc, *rbuff = buff;
	FATFS *fs = FatFs;


	*br = 0;
	if (!fs) return FR_NOT_ENABLED;
	if ((disk_status() & STA_NOINIT) || !fs->fs_type) return FR_NOT_READY;	/* Check disk ready */
	if (fp->flag & FA__ERROR) return FR_RW_ERROR;	/* Check error flag */
	if (!(fp->flag & FA_READ)) return FR_DENIED;	/* Check access mode */
	ln = fp->fsize - fp->fptr;
	if (btr > ln) btr = (uint16)ln;					/* 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 */
			}

			if (fp->flag & FA__DIRTY) {				/* Flush file I/O buffer if needed */
				if (disk_write(fp->buffer, fp->curr_sect, 1) != RES_OK) goto fr_error;
				fp->flag &= ~FA__DIRTY;
			}

			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(rbuff, sect, cc) != RES_OK) goto fr_error;
				fp->sect_clust -= cc - 1;
				fp->curr_sect += cc - 1;
				rcnt = cc * 512; continue;
			}
			if (disk_read(fp->buffer, sect, 1) != RES_OK)	/* Load the sector into file I/O buffer */
				goto fr_error;
		}
		rcnt = 512 - ((uint16)fp->fptr % 512);				/* Copy fractional bytes from file I/O buffer */
		if (rcnt > btr) rcnt = btr;
		memcpy(rbuff, &fp->buffer[fp->fptr % 512], rcnt);
	}

	return FR_OK;

fr_error:	/* Abort this file due to an unrecoverable error */
	fp->flag |= FA__ERROR;
	return FR_RW_ERROR;
}



/*------------*/
/* Write File */

uint16 f_write (
	FIL *fp,			/* Pointer to the file object */
	const void *buff,	/* Pointer to the data to be written */
	uint16 btw,			/* Number of bytes to write */
	uint16 *bw			/* Pointer to number of bytes written */
)
{
	uint32 clust, sect;
	uint16 wcnt;
	uint8 cc;
	const uint8 *wbuff = buff;
	FATFS *fs = FatFs;


	*bw = 0;
	if (!fs) return FR_NOT_ENABLED;
	if ((disk_status() & STA_NOINIT) || !fs->fs_type) return FR_NOT_READY;
	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 */
			}
			if (fp->flag & FA__DIRTY) {				/* Flush file I/O buffer if needed */
				if (disk_write(fp->buffer, fp->curr_sect, 1) != RES_OK) goto fw_error;
				fp->flag &= ~FA__DIRTY;
			}
			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(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) &&  			/* Fill sector buffer with file data if needed */
				(disk_read(fp->buffer, sect, 1) != RES_OK))
					goto fw_error;
		}
		wcnt = 512 - ((uint16)fp->fptr % 512);		/* Copy fractional bytes to file I/O buffer */
		if (wcnt > btw) wcnt = btw;
		memcpy(&fp->buffer[fp->fptr % 512], wbuff, wcnt);
		fp->flag |= FA__DIRTY;
	}

	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 file due to an unrecoverable error */
	fp->flag |= FA__ERROR;
	return FR_RW_ERROR;
}



/*-------------------*/
/* Seek File Pointer */

uint16 f_lseek (
	FIL *fp,		/* Pointer to the file object */
	uint32 ofs		/* File pointer from top of file */
)
{
	uint32 clust;
	uint8 sc;
	FATFS *fs = FatFs;


	if (!fs) return FR_NOT_ENABLED;
	if ((disk_status() & STA_NOINIT) || !fs->fs_type) return FR_NOT_READY;
	if (fp->flag & FA__ERROR) return FR_RW_ERROR;

	if (fp->flag & FA__DIRTY) {			/* Write-back dirty buffer if needed */
		if (disk_write(fp->buffer, fp->curr_sect, 1) != RES_OK) goto fk_error;
		fp->flag &= ~FA__DIRTY;
	}

	if (ofs > fp->fsize) ofs = fp->fsize;	/* Clip offset by file size */
	fp->fptr = ofs; fp->sect_clust = 1; 	/* Re-initialize file pointer */

	/* Seek file pinter if needed */
	if (ofs) {
		ofs = (ofs - 1) / 512;				/* Calcurate current sector */
		sc = fs->sects_clust;				/* Number of sectors in a cluster */
		fp->sect_clust = sc - ((uint8)ofs % sc);	/* Calcurate sector counter */
		ofs /= sc;							/* Number of clusters to skip */
		clust = fp->org_clust;				/* Seek to current cluster */
		while (ofs--)
			clust = get_cluster(clust);
		if ((clust < 2) || (clust >= fs->max_clust)) goto fk_error;
		fp->curr_clust = clust;
		fp->curr_sect = clust2sect(clust) + sc - fp->sect_clust;	/* Current sector */
		if (fp->fptr % 512) {										/* Load currnet sector if needed */
			if (disk_read(fp->buffer, fp->curr_sect, 1) != RES_OK)
				goto fk_error;
		}
	}

	return FR_OK;

fk_error:	/* Abort this file due to an unrecoverable error */
	fp->flag |= FA__ERROR;
	return FR_RW_ERROR;
}



/*-------------------------------------------------*/
/* Synchronize between File and Disk without Close */

uint16 f_sync (
	FIL *fp		/* Pointer to the file object */
)
{
	uint8 *ptr;
	FATFS *fs = FatFs;


	if (!fs) return FR_NOT_ENABLED;
	if ((disk_status() & STA_NOINIT) || !fs->fs_type)
		return FR_INCORRECT_DISK_CHANGE;

	/* Has the file been written? */
	if (fp->flag & FA__WRITTEN) {
		/* Write back data buffer if needed */
		if (fp->flag & FA__DIRTY) {
			if (disk_write(fp->buffer, fp->curr_sect, 1) != RES_OK) return FR_RW_ERROR;
			fp->flag &= ~FA__DIRTY;
		}
		/* Update the directory entry */
		if (!move_window(fp->dir_sect)) return FR_RW_ERROR;
		ptr = fp->dir_ptr;
		*(ptr+11) |= AM_ARC;					/* Set archive bit */
		ST_DWORD(ptr+28, fp->fsize);			/* Update file size */
		ST_WORD(ptr+26, fp->org_clust);			/* Update start cluster */
		ST_WORD(ptr+20, fp->org_clust >> 16);
		ST_DWORD(ptr+22, get_fattime());		/* Updated time */
		fs->winflag = 1;
		fp->flag &= ~FA__WRITTEN;
	}
	if (!move_window(0)) return FR_RW_ERROR;

	return FR_OK;
}



/*------------*/
/* Close File */

uint16 f_close (
	FIL *fp		/* Pointer to the file object to be closed */
)
{
	uint16 res;



	res = f_sync(fp);

	if (res == FR_OK) {
		fp->flag 	= 0;
		FatFs->files--;
	}
	return res;
}



#if _FS_MINIMIZE <= 1
/*---------------------------*/
/* Initialize directroy scan */

uint16 f_opendir (
	DIR *scan,			/* Pointer to directory object to initialize */
	const sint8 *path	/* Pointer to the directory path, null str means the root */
)
{
	uint16 res;
	uint8 *dir;
	sint8 fn[8+3+1];


	if ((res = check_mounted()) != FR_OK) return res;

	res = trace_path(scan, fn, path, &dir);	/* Trace the directory path */

	if (res == FR_OK) {						/* Trace completed */
		if (dir != NULL) {					/* It is not a root dir */
			if (*(dir+11) & AM_DIR) {		/* The entry is a directory */
				scan->clust = ((uint32)LDF_WORD(dir+20) << 16) | LDF_WORD(dir+26);
				scan->sect = clust2sect(scan->clust);
				scan->index = 0;
			} else {						/* The entry is not directory */
				res = FR_NO_FILE;
			}
		}
	}
	return res;
}



/*----------------------------------*/
/* Read Directory Entry in Sequense */

uint16 f_readdir (
	DIR *scan,			/* Pointer to the directory object */
	FILINFO *finfo		/* Pointer to file information to return */
)
{
	uint8 *dir, c;
	FATFS *fs = FatFs;


	if (!fs) return FR_NOT_ENABLED;
	finfo->fname[0] = 0;
	if ((disk_status() & STA_NOINIT) || !fs->fs_type) return FR_NOT_READY;

	while (scan->sect) {
		if (!move_window(scan->sect)) return FR_RW_ERROR;
		dir = &(fs->win[(scan->index & 15) * 32]);		/* pointer to the directory entry */
		c = *dir;
		if (c == 0) break;								/* Has it reached to end of dir? */
		if ((c != 0xE5) && (c != '.') && !(*(dir+11) & AM_VOL))	/* Is it a valid entry? */
			get_fileinfo(finfo, dir);
		if (!next_dir_entry(scan)) scan->sect = 0;		/* Next entry */
		if (finfo->fname[0]) break;						/* Found valid entry */
	}

	return FR_OK;
}



#if _FS_MINIMIZE == 0
/*-----------------*/
/* Get File Status */

uint16 f_stat (
	const sint8 *path,	/* Pointer to the file path */
	FILINFO *finfo		/* Pointer to file information to return */
)
{
	uint16 res;
	uint8 *dir;
	DIR dirscan;
	sint8 fn[8+3+1];


	if ((res = check_mounted()) != FR_OK) return res;

	res = trace_path(&dirscan, fn, path, &dir);	/* Trace the file path */

	if (res == FR_OK)							/* Trace completed */
		get_fileinfo(finfo, dir);

	return res;
}



/*-----------------------------*/
/* Get Number of Free Clusters */

uint16 f_getfree (
	uint32 *nclust		/* Pointer to the double word to return number of free clusters */
)
{
	uint32 n, clust, sect;
	uint8 fat, f, *p;
	uint16 res;
	FATFS *fs = FatFs;


	if ((res = check_mounted()) != FR_OK) return res;

	/* Count number of free clusters */
	fat = fs->fs_type;
	n = 0;
	if (fat == FS_FAT12) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -