PageRenderTime 101ms CodeModel.GetById 22ms app.highlight 72ms RepoModel.GetById 1ms app.codeStats 0ms

/wbudowane/mp3-wave/pff2/src/pff.c

http://momus-projects.googlecode.com/
C | 850 lines | 588 code | 167 blank | 95 comment | 198 complexity | 4ee8c828e2b4aa58c660afad43c3709f MD5 | raw file
  1/*----------------------------------------------------------------------------/
  2/  Petit FatFs - FAT file system module  R0.02                 (C)ChaN, 2009
  3/-----------------------------------------------------------------------------/
  4/ Petit FatFs module is an open source software to implement FAT file system to
  5/ small embedded systems. This is a free software and is opened for education,
  6/ research and commercial developments under license policy of following trems.
  7/
  8/  Copyright (C) 2009, ChaN, all right reserved.
  9/
 10/ * The Petit FatFs module is a free software and there is NO WARRANTY.
 11/ * No restriction on use. You can use, modify and redistribute it for
 12/   personal, non-profit or commercial use UNDER YOUR RESPONSIBILITY.
 13/ * Redistributions of source code must retain the above copyright notice.
 14/
 15/-----------------------------------------------------------------------------/
 16/ Jun 15,'09  R0.01a  First release. (Branched from FatFs R0.07b.)
 17/
 18/ Dec 14,'09  R0.02   Added multiple code page support.
 19/                     Added write funciton.
 20/                     Changed stream read mode interface.
 21/----------------------------------------------------------------------------*/
 22
 23#include "pff.h"		/* Petit FatFs configurations and declarations */
 24#include "diskio.h"		/* Declarations of low level disk I/O functions */
 25
 26
 27/*--------------------------------------------------------------------------
 28
 29   Private Functions
 30
 31---------------------------------------------------------------------------*/
 32
 33static
 34FATFS *FatFs;	/* Pointer to the file system object (logical drive) */
 35
 36
 37
 38/*-----------------------------------------------------------------------*/
 39/* String functions                                                      */
 40/*-----------------------------------------------------------------------*/
 41
 42/* Fill memory */
 43static
 44void mem_set (void* dst, int val, int cnt) {
 45	char *d = (char*)dst;
 46	while (cnt--) *d++ = (char)val;
 47}
 48
 49/* Compare memory to memory */
 50static
 51int mem_cmp (const void* dst, const void* src, int cnt) {
 52	const char *d = (const char *)dst, *s = (const char *)src;
 53	int r = 0;
 54	while (cnt-- && (r = *d++ - *s++) == 0) ;
 55	return r;
 56}
 57
 58
 59
 60/*-----------------------------------------------------------------------*/
 61/* FAT access - Read value of a FAT entry                                */
 62/*-----------------------------------------------------------------------*/
 63
 64static
 65CLUST get_fat (	/* 1:IO error, Else:Cluster status */
 66	CLUST clst	/* Cluster# to get the link information */
 67)
 68{
 69	WORD wc, bc, ofs;
 70	BYTE buf[4];
 71	FATFS *fs = FatFs;
 72
 73
 74	if (clst < 2 || clst >= fs->max_clust)	/* Range check */
 75		return 1;
 76
 77	switch (fs->fs_type) {
 78	case FS_FAT12 :
 79		bc = (WORD)clst; bc += bc / 2;
 80		ofs = bc % 512; bc /= 512;
 81		if (ofs != 511) {
 82			if (disk_readp(buf, fs->fatbase + bc, ofs, 2)) break;
 83		} else {
 84			if (disk_readp(buf, fs->fatbase + bc, 511, 1)) break;
 85			if (disk_readp(buf+1, fs->fatbase + bc + 1, 0, 1)) break;
 86		}
 87		wc = LD_WORD(buf);
 88		return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
 89
 90	case FS_FAT16 :
 91		if (disk_readp(buf, fs->fatbase + clst / 256, (WORD)(((WORD)clst % 256) * 2), 2)) break;
 92		return LD_WORD(buf);
 93#if _FS_FAT32
 94	case FS_FAT32 :
 95		if (disk_readp(buf, fs->fatbase + clst / 128, (WORD)(((WORD)clst % 128) * 4), 4)) break;
 96		return LD_DWORD(buf) & 0x0FFFFFFF;
 97#endif
 98	}
 99
100	return 1;	/* An error occured at the disk I/O layer */
101}
102
103
104
105
106/*-----------------------------------------------------------------------*/
107/* Get sector# from cluster#                                             */
108/*-----------------------------------------------------------------------*/
109
110static
111DWORD clust2sect (	/* !=0: Sector number, 0: Failed - invalid cluster# */
112	CLUST clst		/* Cluster# to be converted */
113)
114{
115	FATFS *fs = FatFs;
116
117
118	clst -= 2;
119	if (clst >= (fs->max_clust - 2)) return 0;		/* Invalid cluster# */
120	return (DWORD)clst * fs->csize + fs->database;
121}
122
123
124
125
126/*-----------------------------------------------------------------------*/
127/* Directory handling - Rewind directory index                           */
128/*-----------------------------------------------------------------------*/
129
130static
131FRESULT dir_rewind (
132	DIR *dj			/* Pointer to directory object */
133)
134{
135	CLUST clst;
136	FATFS *fs = FatFs;
137
138
139	dj->index = 0;
140	clst = dj->sclust;
141	if (clst == 1 || clst >= fs->max_clust)	/* Check start cluster range */
142		return FR_DISK_ERR;
143#if _FS_FAT32
144	if (!clst && fs->fs_type == FS_FAT32)	/* Replace cluster# 0 with root cluster# if in FAT32 */
145		clst = fs->dirbase;
146#endif
147	dj->clust = clst;						/* Current cluster */
148	dj->sect = clst ? clust2sect(clst) : fs->dirbase;	/* Current sector */
149
150	return FR_OK;	/* Seek succeeded */
151}
152
153
154
155
156/*-----------------------------------------------------------------------*/
157/* Directory handling - Move directory index next                        */
158/*-----------------------------------------------------------------------*/
159
160static
161FRESULT dir_next (	/* FR_OK:Succeeded, FR_NO_FILE:End of table */
162	DIR *dj			/* Pointer to directory object */
163)
164{
165	CLUST clst;
166	WORD i;
167	FATFS *fs = FatFs;
168
169
170	i = dj->index + 1;
171	if (!i || !dj->sect)	/* Report EOT when index has reached 65535 */
172		return FR_NO_FILE;
173
174	if (!(i & (16-1))) {	/* Sector changed? */
175		dj->sect++;			/* Next sector */
176
177		if (dj->clust == 0) {	/* Static table */
178			if (i >= fs->n_rootdir)	/* Report EOT when end of table */
179				return FR_NO_FILE;
180		}
181		else {					/* Dynamic table */
182			if (((i / 16) & (fs->csize-1)) == 0) {	/* Cluster changed? */
183				clst = get_fat(dj->clust);		/* Get next cluster */
184				if (clst <= 1) return FR_DISK_ERR;
185				if (clst >= fs->max_clust)		/* When it reached end of dynamic table */
186					return FR_NO_FILE;			/* Report EOT */
187				dj->clust = clst;				/* Initialize data for new cluster */
188				dj->sect = clust2sect(clst);
189			}
190		}
191	}
192
193	dj->index = i;
194
195	return FR_OK;
196}
197
198
199
200
201/*-----------------------------------------------------------------------*/
202/* Directory handling - Find an object in the directory                  */
203/*-----------------------------------------------------------------------*/
204
205static
206FRESULT dir_find (
207	DIR *dj			/* Pointer to the directory object linked to the file name */
208)
209{
210	FRESULT res;
211	BYTE c, *dir;
212
213
214	res = dir_rewind(dj);			/* Rewind directory object */
215	if (res != FR_OK) return res;
216
217	dir = FatFs->buf;
218	do {
219		res = disk_readp(dir, dj->sect, (WORD)((dj->index % 16) * 32), 32)	/* Read an entry */
220			? FR_DISK_ERR : FR_OK;
221		if (res != FR_OK) break;
222		c = dir[DIR_Name];	/* First character */
223		if (c == 0) { res = FR_NO_FILE; break; }	/* Reached to end of table */
224		if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
225			break;
226		res = dir_next(dj);							/* Next entry */
227	} while (res == FR_OK);
228
229	return res;
230}
231
232
233
234
235/*-----------------------------------------------------------------------*/
236/* Read an object from the directory                                     */
237/*-----------------------------------------------------------------------*/
238#if _USE_DIR
239static
240FRESULT dir_read (
241	DIR *dj			/* Pointer to the directory object to store read object name */
242)
243{
244	FRESULT res;
245	BYTE a, c, *dir;
246
247
248	res = FR_NO_FILE;
249	dir = FatFs->buf;
250	while (dj->sect) {
251		res = disk_readp(dir, dj->sect, (WORD)((dj->index % 16) * 32), 32)	/* Read an entry */
252			? FR_DISK_ERR : FR_OK;
253		if (res != FR_OK) break;
254		c = dir[DIR_Name];
255		if (c == 0) { res = FR_NO_FILE; break; }	/* Reached to end of table */
256		a = dir[DIR_Attr] & AM_MASK;
257		if (c != 0xE5 && c != '.' && !(a & AM_VOL))	/* Is it a valid entry? */
258			break;
259		res = dir_next(dj);				/* Next entry */
260		if (res != FR_OK) break;
261	}
262
263	if (res != FR_OK) dj->sect = 0;
264
265	return res;
266}
267#endif
268
269
270
271/*-----------------------------------------------------------------------*/
272/* Pick a segment and create the object name in directory form           */
273/*-----------------------------------------------------------------------*/
274
275#ifdef _EXCVT
276	static const BYTE cvt[] = _EXCVT;
277#endif
278
279static
280FRESULT create_name (
281	DIR *dj,			/* Pointer to the directory object */
282	const char **path	/* Pointer to pointer to the segment in the path string */
283)
284{
285	BYTE c, d, ni, si, i, *sfn;
286	const char *p;
287
288	/* Create file name in directory form */
289	sfn = dj->fn;
290	mem_set(sfn, ' ', 11);
291	si = i = 0; ni = 8;
292	p = *path;
293	for (;;) {
294		c = p[si++];
295		if (c <= ' ' || c == '/') break;	/* Break on end of segment */
296		if (c == '.' || i >= ni) {
297			if (ni != 8 || c != '.') break;
298			i = 8; ni = 11;
299			continue;
300		}
301#ifdef _EXCVT
302		if (c >= 0x80)					/* To upper extended char (SBCS) */
303			c = cvt[c - 0x80];
304#endif
305		if (IsDBCS1(c) && i >= ni - 1) {	/* DBC 1st byte? */
306			d = p[si++];					/* Get 2nd byte */
307			sfn[i++] = c;
308			sfn[i++] = d;
309		} else {						/* Single byte code */
310			if (IsLower(c)) c -= 0x20;	/* toupper */
311			sfn[i++] = c;
312		}
313	}
314	*path = &p[si];						/* Rerurn pointer to the next segment */
315
316	sfn[11] = (c <= ' ') ? 1 : 0;		/* Set last segment flag if end of path */
317
318	return FR_OK;
319}
320
321
322
323
324/*-----------------------------------------------------------------------*/
325/* Get file information from directory entry                             */
326/*-----------------------------------------------------------------------*/
327#if _USE_DIR
328static
329void get_fileinfo (		/* No return code */
330	DIR *dj,			/* Pointer to the directory object */
331	FILINFO *fno	 	/* Pointer to store the file information */
332)
333{
334	BYTE i, c, *dir;
335	char *p;
336
337
338	p = fno->fname;
339	if (dj->sect) {
340		dir = FatFs->buf;
341		for (i = 0; i < 8; i++) {	/* Copy file name body */
342			c = dir[i];
343			if (c == ' ') break;
344			if (c == 0x05) c = 0xE5;
345			*p++ = c;
346		}
347		if (dir[8] != ' ') {		/* Copy file name extension */
348			*p++ = '.';
349			for (i = 8; i < 11; i++) {
350				c = dir[i];
351				if (c == ' ') break;
352				*p++ = c;
353			}
354		}
355		fno->fattrib = dir[DIR_Attr];				/* Attribute */
356		fno->fsize = LD_DWORD(dir+DIR_FileSize);	/* Size */
357		fno->fdate = LD_WORD(dir+DIR_WrtDate);		/* Date */
358		fno->ftime = LD_WORD(dir+DIR_WrtTime);		/* Time */
359	}
360	*p = 0;
361}
362#endif /* _USE_DIR */
363
364
365
366/*-----------------------------------------------------------------------*/
367/* Follow a file path                                                    */
368/*-----------------------------------------------------------------------*/
369
370static
371FRESULT follow_path (	/* FR_OK(0): successful, !=0: error code */
372	DIR *dj,			/* Directory object to return last directory and found object */
373	const char *path	/* Full-path string to find a file or directory */
374)
375{
376	FRESULT res;
377	BYTE *dir;
378
379
380	while (*path == ' ') path++;		/* Skip leading spaces */
381	if (*path == '/') path++;			/* Strip heading separator */
382	dj->sclust = 0;						/* Set start directory (always root dir) */
383
384	if ((BYTE)*path <= ' ') {			/* Null path means the root directory */
385		res = dir_rewind(dj);
386		FatFs->buf[0] = 0;
387
388	} else {							/* Follow path */
389		for (;;) {
390			res = create_name(dj, &path);	/* Get a segment */
391			if (res != FR_OK) break;
392			res = dir_find(dj);				/* Find it */
393			if (res != FR_OK) {				/* Could not find the object */
394				if (res == FR_NO_FILE && !*(dj->fn+11))
395					res = FR_NO_PATH;
396				break;
397			}
398			if (*(dj->fn+11)) break;		/* Last segment match. Function completed. */
399			dir = FatFs->buf;				/* There is next segment. Follow the sub directory */
400			if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
401				res = FR_NO_PATH; break;
402			}
403			dj->sclust =
404#if _FS_FAT32
405				((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | 
406#endif
407				LD_WORD(dir+DIR_FstClusLO);
408		}
409	}
410
411	return res;
412}
413
414
415
416
417/*-----------------------------------------------------------------------*/
418/* Check a sector if it is an FAT boot record                            */
419/*-----------------------------------------------------------------------*/
420
421static
422BYTE check_fs (	/* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record, 3:Error */
423	BYTE *buf,	/* Working buffer */
424	DWORD sect	/* Sector# (lba) to check if it is an FAT boot record or not */
425)
426{
427	if (disk_readp(buf, sect, 510, 2))		/* Read the boot sector */
428		return 3;
429	if (LD_WORD(buf) != 0xAA55)				/* Check record signature */
430		return 2;
431
432	if (!disk_readp(buf, sect, BS_FilSysType, 2) && LD_WORD(buf) == 0x4146)	/* Check FAT12/16 */
433		return 0;
434#if _FS_FAT32
435	if (!disk_readp(buf, sect, BS_FilSysType32, 2) && LD_WORD(buf) == 0x4146)	/* Check FAT32 */
436		return 0;
437#endif
438	return 1;
439}
440
441
442
443
444/*--------------------------------------------------------------------------
445
446   Public Functions
447
448--------------------------------------------------------------------------*/
449
450
451
452/*-----------------------------------------------------------------------*/
453/* Mount/Unmount a Locical Drive                                         */
454/*-----------------------------------------------------------------------*/
455
456FRESULT pf_mount (
457	FATFS *fs		/* Pointer to new file system object (NULL: Unmount) */
458)
459{
460	BYTE fmt, buf[36];
461	DWORD bsect, fsize, tsect, mclst;
462
463
464	FatFs = 0;
465	if (!fs) return FR_OK;				/* Unregister fs object */
466
467	if (disk_initialize() & STA_NOINIT)	/* Check if the drive is ready or not */
468		return FR_NOT_READY;
469
470	/* Search FAT partition on the drive */
471	bsect = 0;
472	fmt = check_fs(buf, bsect);			/* Check sector 0 as an SFD format */
473	if (fmt == 1) {						/* Not an FAT boot record, it may be FDISK format */
474		/* Check a partition listed in top of the partition table */
475		if (disk_readp(buf, bsect, MBR_Table, 16)) {	/* 1st partition entry */
476			fmt = 3;
477		} else {
478			if (buf[4]) {					/* Is the partition existing? */
479				bsect = LD_DWORD(&buf[8]);	/* Partition offset in LBA */
480				fmt = check_fs(buf, bsect);	/* Check the partition */
481			}
482		}
483	}
484	if (fmt == 3) return FR_DISK_ERR;
485	if (fmt) return FR_NO_FILESYSTEM;	/* No valid FAT patition is found */
486
487	/* Initialize the file system object */
488	if (disk_readp(buf, bsect, 13, sizeof(buf))) return FR_DISK_ERR;
489
490	fsize = LD_WORD(buf+BPB_FATSz16-13);				/* Number of sectors per FAT */
491	if (!fsize) fsize = LD_DWORD(buf+BPB_FATSz32-13);
492
493	fsize *= buf[BPB_NumFATs-13];						/* Number of sectors in FAT area */
494	fs->fatbase = bsect + LD_WORD(buf+BPB_RsvdSecCnt-13); /* FAT start sector (lba) */
495	fs->csize = buf[BPB_SecPerClus-13];					/* Number of sectors per cluster */
496	fs->n_rootdir = LD_WORD(buf+BPB_RootEntCnt-13);		/* Nmuber of root directory entries */
497	tsect = LD_WORD(buf+BPB_TotSec16-13);				/* Number of sectors on the file system */
498	if (!tsect) tsect = LD_DWORD(buf+BPB_TotSec32-13);
499	mclst = (tsect						/* Last cluster# + 1 */
500		- LD_WORD(buf+BPB_RsvdSecCnt-13) - fsize - fs->n_rootdir / 16
501		) / fs->csize + 2;
502	fs->max_clust = (CLUST)mclst;
503
504	fmt = FS_FAT12;							/* Determine the FAT sub type */
505	if (mclst >= 0xFF7) fmt = FS_FAT16;		/* Number of clusters >= 0xFF5 */
506	if (mclst >= 0xFFF7)					/* Number of clusters >= 0xFFF5 */
507#if _FS_FAT32
508		fmt = FS_FAT32;
509#else
510		return FR_NO_FILESYSTEM;
511#endif
512
513	fs->fs_type = fmt;		/* FAT sub-type */
514#if _FS_FAT32
515	if (fmt == FS_FAT32)
516		fs->dirbase = LD_DWORD(buf+(BPB_RootClus-13));	/* Root directory start cluster */
517	else
518#endif
519		fs->dirbase = fs->fatbase + fsize;				/* Root directory start sector (lba) */
520	fs->database = fs->fatbase + fsize + fs->n_rootdir / 16;	/* Data start sector (lba) */
521
522	fs->flag = 0;
523	FatFs = fs;
524
525	return FR_OK;
526}
527
528
529
530
531/*-----------------------------------------------------------------------*/
532/* Open or Create a File                                                 */
533/*-----------------------------------------------------------------------*/
534
535FRESULT pf_open (
536	const char *path	/* Pointer to the file name */
537)
538{
539	FRESULT res;
540	DIR dj;
541	BYTE sp[12], dir[32];
542	FATFS *fs = FatFs;
543
544
545	if (!fs)						/* Check file system */
546		return FR_NOT_ENABLED;
547
548	fs->flag = 0;
549	fs->buf = dir;
550	dj.fn = sp;
551	res = follow_path(&dj, path);	/* Follow the file path */
552	if (res != FR_OK) return res;	/* Follow failed */
553	if (!dir[0] || (dir[DIR_Attr] & AM_DIR))	/* It is a directory */
554		return FR_NO_FILE;
555
556	fs->org_clust =						/* File start cluster */
557#if _FS_FAT32
558		((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) |
559#endif
560		LD_WORD(dir+DIR_FstClusLO);
561	fs->fsize = LD_DWORD(dir+DIR_FileSize);	/* File size */
562	fs->fptr = 0;						/* File pointer */
563	fs->flag = FA_OPENED;
564
565	return FR_OK;
566}
567
568
569
570
571/*-----------------------------------------------------------------------*/
572/* Read File                                                             */
573/*-----------------------------------------------------------------------*/
574#if _USE_READ
575
576DRESULT dr;
577CLUST clst;
578DWORD sect, remain;
579BYTE *rbuff;
580WORD rcnt;
581FATFS *fs;
582
583FRESULT pf_read (
584	void* buff,		/* Pointer to the read buffer (NULL:Forward data to the stream)*/
585	WORD btr,		/* Number of bytes to read */
586	WORD* br		/* Pointer to number of bytes read */
587)
588{
589	//DRESULT dr;
590	//CLUST clst;
591	//DWORD sect, remain;
592	rbuff = buff;
593	//WORD rcnt;
594	fs = FatFs;
595
596
597	*br = 0;
598	if (!fs) return FR_NOT_ENABLED;		/* Check file system */
599	if (!(fs->flag & FA_OPENED))		/* Check if opened */
600		return FR_NOT_OPENED;
601
602	remain = fs->fsize - fs->fptr;
603	if (btr > remain) btr = (WORD)remain;			/* Truncate btr by remaining bytes */
604
605	while (btr)	{									/* Repeat until all data transferred */
606		if ((fs->fptr % 512) == 0) {				/* On the sector boundary? */
607			if ((fs->fptr / 512 % fs->csize) == 0) {	/* On the cluster boundary? */
608				clst = (fs->fptr == 0) ?			/* On the top of the file? */
609					fs->org_clust : get_fat(fs->curr_clust);
610				if (clst <= 1) goto fr_abort;
611				fs->curr_clust = clst;				/* Update current cluster */
612				fs->csect = 0;						/* Reset sector offset in the cluster */
613			}
614			sect = clust2sect(fs->curr_clust);		/* Get current sector */
615			if (!sect) goto fr_abort;
616			fs->dsect = sect + fs->csect++;
617		}
618		rcnt = 512 - ((WORD)fs->fptr % 512);		/* Get partial sector data from sector buffer */
619		if (rcnt > btr) rcnt = btr;
620		dr = disk_readp(!buff ? 0 : rbuff, fs->dsect, (WORD)(fs->fptr % 512), rcnt);
621		if (dr) goto fr_abort;
622		fs->fptr += rcnt; rbuff += rcnt;			/* Update pointers and counters */
623		btr -= rcnt; *br += rcnt;
624	}
625
626	return FR_OK;
627
628fr_abort:
629	fs->flag = 0;
630	return FR_DISK_ERR;
631}
632#endif
633
634
635
636/*-----------------------------------------------------------------------*/
637/* Write File                                                            */
638/*-----------------------------------------------------------------------*/
639#if _USE_WRITE
640
641FRESULT pf_write (
642	const void* buff,	/* Pointer to the data to be written */
643	WORD btw,			/* Number of bytes to write (0:Finalize the current write operation) */
644	WORD* bw			/* Pointer to number of bytes written */
645)
646{
647	CLUST clst;
648	DWORD sect, remain;
649	const BYTE *p = buff;
650	WORD wcnt;
651	FATFS *fs = FatFs;
652
653
654	*bw = 0;
655	if (!fs) return FR_NOT_ENABLED;		/* Check file system */
656	if (!(fs->flag & FA_OPENED))		/* Check if opened */
657		return FR_NOT_OPENED;
658
659	if (!btw) {		/* Finalize request */
660		if ((fs->flag & FA__WIP) && disk_writep(0, 0)) goto fw_abort;
661		fs->flag &= ~FA__WIP;
662		return FR_OK;
663	} else {		/* Write data request */
664		if (!(fs->flag & FA__WIP))		/* Round down fptr to the sector boundary */
665			fs->fptr &= 0xFFFFFE00;
666	}
667	remain = fs->fsize - fs->fptr;
668	if (btw > remain) btw = (WORD)remain;			/* Truncate btw by remaining bytes */
669
670	while (btw)	{									/* Repeat until all data transferred */
671		if (((WORD)fs->fptr % 512) == 0) {				/* On the sector boundary? */
672			if ((fs->fptr / 512 % fs->csize) == 0) {	/* On the cluster boundary? */
673				clst = (fs->fptr == 0) ?			/* On the top of the file? */
674					fs->org_clust : get_fat(fs->curr_clust);
675				if (clst <= 1) goto fw_abort;
676				fs->curr_clust = clst;				/* Update current cluster */
677				fs->csect = 0;						/* Reset sector offset in the cluster */
678			}
679			sect = clust2sect(fs->curr_clust);		/* Get current sector */
680			if (!sect) goto fw_abort;
681			fs->dsect = sect + fs->csect++;
682			if (disk_writep(0, fs->dsect)) goto fw_abort;	/* Initiate a sector write operation */
683			fs->flag |= FA__WIP;
684		}
685		wcnt = 512 - ((WORD)fs->fptr % 512);		/* Number of bytes to write to the sector */
686		if (wcnt > btw) wcnt = btw;
687		if (disk_writep(p, wcnt)) goto fw_abort;	/* Send data to the sector */
688		fs->fptr += wcnt; p += wcnt;				/* Update pointers and counters */
689		btw -= wcnt; *bw += wcnt;
690		if (((WORD)fs->fptr % 512) == 0) {
691			if (disk_writep(0, 0)) goto fw_abort;	/* Finalize the currtent secter write operation */
692			fs->flag &= ~FA__WIP;
693		}
694	}
695
696	return FR_OK;
697
698fw_abort:
699	fs->flag = 0;
700	return FR_DISK_ERR;
701}
702#endif
703
704
705
706/*-----------------------------------------------------------------------*/
707/* Seek File R/W Pointer                                                 */
708/*-----------------------------------------------------------------------*/
709#if _USE_LSEEK
710
711FRESULT pf_lseek (
712	DWORD ofs		/* File pointer from top of file */
713)
714{
715	CLUST clst;
716	DWORD bcs, sect, ifptr;
717	FATFS *fs = FatFs;
718
719
720	if (!fs) return FR_NOT_ENABLED;		/* Check file system */
721	if (!(fs->flag & FA_OPENED))		/* Check if opened */
722			return FR_NOT_OPENED;
723
724	if (ofs > fs->fsize) ofs = fs->fsize;	/* Clip offset with the file size */
725	ifptr = fs->fptr;
726	fs->fptr = 0;
727	if (ofs > 0) {
728		bcs = (DWORD)fs->csize * 512;	/* Cluster size (byte) */
729		if (ifptr > 0 &&
730			(ofs - 1) / bcs >= (ifptr - 1) / bcs) {	/* When seek to same or following cluster, */
731			fs->fptr = (ifptr - 1) & ~(bcs - 1);	/* start from the current cluster */
732			ofs -= fs->fptr;
733			clst = fs->curr_clust;
734		} else {							/* When seek to back cluster, */
735			clst = fs->org_clust;			/* start from the first cluster */
736			fs->curr_clust = clst;
737		}
738		while (ofs > bcs) {				/* Cluster following loop */
739			clst = get_fat(clst);		/* Follow cluster chain */
740			if (clst <= 1 || clst >= fs->max_clust) goto fe_abort;
741			fs->curr_clust = clst;
742			fs->fptr += bcs;
743			ofs -= bcs;
744		}
745		fs->fptr += ofs;
746		sect = clust2sect(clst);		/* Current sector */
747		if (!sect) goto fe_abort;
748		fs->csect = (BYTE)(ofs / 512);	/* Sector offset in the cluster */
749		if (ofs % 512)
750			fs->dsect = sect + fs->csect++;
751	}
752
753	return FR_OK;
754
755fe_abort:
756	fs->flag = 0;
757	return FR_DISK_ERR;
758}
759#endif
760
761
762
763/*-----------------------------------------------------------------------*/
764/* Create a Directroy Object                                             */
765/*-----------------------------------------------------------------------*/
766#if _USE_DIR
767
768FRESULT pf_opendir (
769	DIR *dj,			/* Pointer to directory object to create */
770	const char *path	/* Pointer to the directory path */
771)
772{
773	FRESULT res;
774	BYTE sp[12], dir[32];
775	FATFS *fs = FatFs;
776
777
778	if (!fs) {				/* Check file system */
779		res = FR_NOT_ENABLED;
780	} else {
781		fs->buf = dir;
782		dj->fn = sp;
783		res = follow_path(dj, path);			/* Follow the path to the directory */
784		if (res == FR_OK) {						/* Follow completed */
785			if (dir[0]) {						/* It is not the root dir */
786				if (dir[DIR_Attr] & AM_DIR) {	/* The object is a directory */
787					dj->sclust =
788#if _FS_FAT32
789					((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) |
790#endif
791					LD_WORD(dir+DIR_FstClusLO);
792				} else {						/* The object is not a directory */
793					res = FR_NO_PATH;
794				}
795			}
796			if (res == FR_OK)
797				res = dir_rewind(dj);			/* Rewind dir */
798		}
799		if (res == FR_NO_FILE) res = FR_NO_PATH;
800	}
801
802	return res;
803}
804
805
806
807
808/*-----------------------------------------------------------------------*/
809/* Read Directory Entry in Sequense                                      */
810/*-----------------------------------------------------------------------*/
811
812FRESULT pf_readdir (
813	DIR *dj,			/* Pointer to the open directory object */
814	FILINFO *fno		/* Pointer to file information to return */
815)
816{
817	FRESULT res;
818	BYTE sp[12], dir[32];
819	FATFS *fs = FatFs;
820
821
822	if (!fs) {				/* Check file system */
823		res = FR_NOT_ENABLED;
824	} else {
825		fs->buf = dir;
826		dj->fn = sp;
827		if (!fno) {
828			res = dir_rewind(dj);
829		} else {
830			res = dir_read(dj);
831			if (res == FR_NO_FILE) {
832				dj->sect = 0;
833				res = FR_OK;
834			}
835			if (res == FR_OK) {				/* A valid entry is found */
836				get_fileinfo(dj, fno);		/* Get the object information */
837				res = dir_next(dj);			/* Increment index for next */
838				if (res == FR_NO_FILE) {
839					dj->sect = 0;
840					res = FR_OK;
841				}
842			}
843		}
844	}
845
846	return res;
847}
848
849#endif /* _USE_DIR */
850