From f9a05f6edaf54d307083b24ae7e0cb2de6ba9a6d Mon Sep 17 00:00:00 2001 From: savelij13 Date: Thu, 11 Sep 2025 09:58:52 +0300 Subject: [PATCH] fatfs v0.10 Oct 02,2013: - Added selection of character encoding on the file. (_STRF_ENCODE) - Added f_closedir(). - Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO) - Added forced mount feature with changes of f_mount(). - Improved behavior of volume auto detection. - Improved write throughput of f_puts() and f_printf(). - Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write(). - Fixed f_write() can be truncated when the file size is close to 4GB. - Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect error code. --- doc/00index_e.html | 33 +- doc/00index_j.html | 32 +- doc/en/appnote.html | 51 +- doc/en/chdrive.html | 6 +- doc/en/chmod.html | 6 +- doc/en/close.html | 3 +- doc/en/closedir.html | 64 ++ doc/en/dinit.html | 2 +- doc/en/dread.html | 4 +- doc/en/dwrite.html | 4 +- doc/en/error.html | 2 +- doc/en/fdisk.html | 20 +- doc/en/filename.html | 21 +- doc/en/getcwd.html | 2 +- doc/en/getfree.html | 8 +- doc/en/getlabel.html | 6 +- doc/en/gets.html | 4 +- doc/en/lseek.html | 22 +- doc/en/mkfs.html | 18 +- doc/en/mount.html | 36 +- doc/en/open.html | 73 +- doc/en/opendir.html | 9 +- doc/en/printf.html | 14 +- doc/en/putc.html | 4 +- doc/en/puts.html | 6 +- doc/en/rc.html | 2 +- doc/en/readdir.html | 18 +- doc/en/rename.html | 8 +- doc/en/sdir.html | 7 +- doc/en/setlabel.html | 4 +- doc/en/sfatfs.html | 15 +- doc/en/sfile.html | 14 +- doc/en/sfileinfo.html | 6 +- doc/en/stat.html | 8 +- doc/en/sync.html | 3 +- doc/en/unlink.html | 8 +- doc/en/utime.html | 6 +- doc/img/app1.c | 5 +- doc/img/app2.c | 7 +- doc/img/app3.c | 46 +- doc/img/modules.png | Bin 4652 -> 8624 bytes doc/ja/appnote.html | 35 +- doc/ja/chdrive.html | 6 +- doc/ja/chmod.html | 12 +- doc/ja/close.html | 1 + doc/ja/closedir.html | 64 ++ doc/ja/dioctl.html | 10 +- doc/ja/dread.html | 18 +- doc/ja/dstat.html | 6 +- doc/ja/dwrite.html | 4 +- doc/ja/error.html | 2 +- doc/ja/fdisk.html | 18 +- doc/ja/filename.html | 11 +- doc/ja/getcwd.html | 2 +- doc/ja/getfree.html | 8 +- doc/ja/gets.html | 2 +- doc/ja/lseek.html | 18 +- doc/ja/mkfs.html | 14 +- doc/ja/mount.html | 35 +- doc/ja/open.html | 71 +- doc/ja/opendir.html | 11 +- doc/ja/printf.html | 12 +- doc/ja/putc.html | 4 +- doc/ja/puts.html | 4 +- doc/ja/rc.html | 2 +- doc/ja/readdir.html | 17 +- doc/ja/rename.html | 6 +- doc/ja/sdir.html | 9 +- doc/ja/sfatfs.html | 17 +- doc/ja/sfile.html | 12 +- doc/ja/sfileinfo.html | 2 +- doc/ja/stat.html | 9 +- doc/ja/sync.html | 3 +- doc/ja/unlink.html | 8 +- doc/ja/utime.html | 4 +- doc/updates.txt | 11 + src/00readme.txt | 13 +- src/diskio.c | 4 +- src/diskio.h | 4 +- src/ff.c | 1467 +++++++++++++++++++++++------------------ src/ff.h | 58 +- src/ffconf.h | 114 ++-- src/integer.h | 22 +- 83 files changed, 1636 insertions(+), 1121 deletions(-) create mode 100644 doc/en/closedir.html create mode 100644 doc/ja/closedir.html diff --git a/doc/00index_e.html b/doc/00index_e.html index 1bdedbf..dc89108 100644 --- a/doc/00index_e.html +++ b/doc/00index_e.html @@ -42,36 +42,37 @@

Application Interface

FatFs module provides following functions to the applications. In other words, this list describes what FatFs can do to access the FAT volumes.

-

_USE_FASTSEEKが1で、且つファイル・オブジェクトのcltblメンバがNULL以外(f_open()でNULLに設定される)のとき、高速シーク・モードになります。これはファイルのクラスタ配置情報(CLMT)をメモリ上に保持しておくことにより、FATにアクセスすることなく後方シークやロング・シークを高速に行う機能です。高速シーク・モードは、f_read()/f_wtite()の動作にも適用されます。高速シーク・モードではf_wtite()/f_lseek()によるファイル・サイズの拡張はできません。

+

_USE_FASTSEEKが1で、且つファイル・オブジェクトのcltblメンバがNULL以外(f_open()でNULLに設定される)のとき、高速シーク・モードになります。これはファイルのクラスタ配置情報(CLMT)をメモリ上に保持しておくことにより、FATにアクセスすることなく後方シークやロング・シークを高速に行う機能です。高速シーク・モードは、f_read()/f_wtite()の動作にも適用されます。高速シーク・モードではf_wtite()/f_lseek()によるファイル・サイズの拡張はできません。

高速シーク動作を行う前に、CLMTを作成しておく必要があります。これを作成するには、まずCLMT格納バッファ(DWORD型配列)を準備し、cltblメンバにそのポインタをセットします。そして、配列の先頭要素にその配列のサイズ(要素数)を入れ、f_lseek()ofsCREATE_LINKMAPを指定して呼び出します。関数が成功するとCLMTが作成され、以降のf_read()/f_write()/f_lseek()ではFATへのアクセスは発生しません。FR_NOT_ENOUGH_COREで失敗したときは配列サイズが不足で、先頭要素には実際に必要となる要素数が返されます。必要な要素数は、(ファイルの分割数 + 1) * 2 です。たとえば、ファイルが5つのフラグメントに分断されているときに必要な要素数は、12となります。

@@ -69,7 +69,7 @@ FRESULT f_lseek (

使用例

     /* ファイルを開く */
-    fp = malloc(sizeof(FIL));
+    fp = malloc(sizeof (FIL));
     res = f_open(fp, "file.dat", FA_READ|FA_WRITE);
     if (res) ...
 
@@ -82,11 +82,11 @@ FRESULT f_lseek (
     /* 3000バイト進める */
     res = f_lseek(fp, f_tell(fp) + 3000);
 
-    /* 2000バイト戻す (オーバーフローに注意) */
+    /* 2000バイト戻す (ラップアラウンドに注意) */
     res = f_lseek(fp, f_tell(fp) - 2000);
 
-    /* クラスタ先行割り当て (ストリーミング・ライト時のバッファ・オーバーラン防止) */
+/* クラスタ先行割り当て (ストリーミング・ライト時のバッファ・オーバーラン防止) */
 
     res = f_open(fp, "record.wav", FA_CREATE_NEW | FA_WRITE);    /* ファイル作成 */
 
@@ -103,18 +103,18 @@ FRESULT f_lseek (
     res = f_close(fp);
 
-    /* 高速シーク機能を使う */
+/* 高速シーク機能を使う */
 
-    DWORD lktbl[SZ_TBL];                   /* リンク・マップ・テーブル格納バッファ */
+    DWORD clmt[SZ_TBL];                    /* リンク・マップ・テーブル格納バッファ */
 
     res = f_lseek(fp, ofs1);               /* 通常シーク (オープン時、cltblはNULLに初期化される) */
 
-    fp->cltbl = lktbl;                     /* 高速シーク機能の有効化 (cltbl != NULL) */
-    lktbl[0] = SZ_TBL;                     /* 先頭要素に配列要素数をセット */
+    fp->cltbl = clmt;                      /* 高速シーク機能の有効化 */
+    clmt[0] = SZ_TBL;                      /* 先頭要素に配列要素数をセット */
     res = f_lseek(fp, CREATE_LINKMAP);     /* CLMTの作成 */
     ...
 
-    res = f_lseek(fp, ofs2);               /* 以降、f_read/f_write/f_lseekでFATアクセスが発生しない */
+    res = f_lseek(fp, ofs2);               /* 以降、f_read/f_write/f_lseekでFATアクセスは発生しない */
 
diff --git a/doc/ja/mkfs.html b/doc/ja/mkfs.html index 130cd9f..a9b5ceb 100644 --- a/doc/ja/mkfs.html +++ b/doc/ja/mkfs.html @@ -16,9 +16,9 @@

論理ドライブ上にFATボリュームを作成(フォーマット)します。

 FRESULT f_mkfs (
-  BYTE  vol,   /* [IN] 論理ドライブ番号 */
-  BYTE  sfd,   /* [IN] 区画作成方法 */
-  UINT  au     /* [IN] クラス・タサイズ */
+  const TCHAR* path, /* [IN] 論理ドライブ番号 */
+  BYTE  sfd,         /* [IN] 区画作成方法 */
+  UINT  au           /* [IN] クラス・タサイズ */
 );
 
@@ -26,10 +26,10 @@ FRESULT f_mkfs (

引数

-
vol
-
フォーマットする論理ドライブ。(0 〜 _VOLUMES - 1)
+
path
+
フォーマット対象の論理ドライブを示すパス名を示すヌル文字'\0'終端の文字列へのポインタを指定します。ドライブ番号を含まない場合は、カレント・ドライブを意味します。
sfd
-
パーテーション形式。(0(FDISK) or 1(SFD))
+
パーテーション形式。(0(FDISK) または 1(SFD))
au
クラスタ・サイズをバイト単位で指定します。対象ドライブのセクタ・サイズのn倍(n = 1〜128で、2の累乗)でなければなりません。0を指定した場合、ボリュームのサイズに応じたデフォルトのクラスタ・サイズが選択されます。
@@ -51,7 +51,7 @@ FRESULT f_mkfs (

説明

物理ドライブ上にFATボリュームを作成します。FDISK形式が指定された場合は、物理ドライブ全体を占める基本区画(パーテーション)が作成され、その中にFATボリュームが作成されます。SFD形式では、FATボリュームは物理ドライブの先頭セクタからベタで作成されます。

マルチパーテーション機能(_MULTI_PARTITION)により、指定された論理ドライブが特定の区画(1〜4)に結び付けられている場合、その区画の中にFATボリュームが作成されます。この場合、sfdは無視され、また対応する物理ドライブはこれに先立ち、f_fdisk()または他のツールで適切に区画設定されている必要があります。

-

パーテーション形式には、FDISK形式とSFD形式の二通りあります。FDISK形式は、ハードディスク、MMC、SDC、CFCなどで使用されます。FDISK形式では一台の物理ドライブ上に一つまたは複数の区画を作成することができます。管理情報はMBR(物理ドライブの先頭セクタ)に記録されます。SFD形式は単に何の分割も行わない形式で、ボリュームは物理ドライブの先頭セクタから開始します。SFD形式は、フロッピーディスク、マイクロドライブ、光学ディスク、およびその他スーパーフロッピーメディアで使用されています。

+

パーテーション形式には、FDISK形式とSFD形式の二通りあります。FDISK形式は、ハードディスク、MMC、SDC、CFC、U Diskなどで標準的に使用されます。FDISK形式では一台の物理ドライブ上に一つまたは複数の区画を作成することができます。管理情報はMBR(物理ドライブの先頭セクタ)に記録されます。SFD形式は単に何の分割も行わない形式で、ボリュームは物理ドライブの先頭セクタから開始します。SFD形式は、フロッピーディスク、マイクロドライブ、光学ディスク、およびその他スーパーフロッピーメディアで標準的に使用されています。

FATタイプ(FAT12/FAT16/FAT32)は、その論理ドライブ上のクラスタ数によってのみ決定される決まり[FAT仕様書より]になっていて、それ以外の要因はありません。したがって、どのFATタイプになるかはドライブ・サイズとクラスタ・サイズに依存します。クラスタ・サイズは大きくするほど性能が上がり、ディスク利用効率は落ちます。

クラスタ数がFATタイプの境界に近くなるときは、FR_MKFS_ABORTEDで関数が失敗する可能性があります。

diff --git a/doc/ja/mount.html b/doc/ja/mount.html index e057d5b..7ad05d9 100644 --- a/doc/ja/mount.html +++ b/doc/ja/mount.html @@ -16,8 +16,9 @@

論理ドライブにファイル・システム・オブジェクトを登録・抹消します。

 FRESULT f_mount (
-  BYTE  vol,      /* [IN] 論理ドライブ番号 */
-  FATFS*  fatfs   /* [IN] ワーク・エリアへのポインタ */
+  FATFS*       fatfs,  /* [IN] ファイル・システム・オブジェクト */
+  const TCHAR* path,   /* [IN] 論理ドライブ番号 */
+  BYTE         opt     /* [IN] オプション */
 );
 
@@ -25,10 +26,12 @@ FRESULT f_mount (

引数

-
vol
-
論理ドライブ番号(0 〜 _VOLUMES - 1)。
fatfs
登録するファイル・システム・オブジェクトへのポインタ。
+
path
+
対象となる論理ドライブのパス名を示すヌル文字'\0'終端の文字列へのポインタを指定します。ドライブ番号を含まない場合は、デフォルト・ドライブを指定したことになります。
+
opt
+
ファイル・システム・オブジェクトの登録と同時にマウント動作を行うかどうかを指定するフラグ。登録抹消のときは意味を持ちません。
@@ -36,20 +39,30 @@ FRESULT f_mount (

戻り値

FR_OK, -FR_INVALID_DRIVE +FR_INVALID_DRIVE, +FR_DISK_ERR, +FR_NOT_READY, +FR_NO_FILESYSTEM

解説

-

FatFsモジュールでは、それぞれの論理ドライブにファイル・システム・オブジェクトというワーク・エリアが必要です。この関数は論理ドライブにそのワーク・エリアを登録したり抹消したりします。何らかのファイル関数を使用する前に、この関数でその論理ドライブのワーク・エリアを与えておかなければなりません。fatfsにヌル・ポインタを指定するとワーク・エリアの登録は抹消され、登録されていたワーク・エリアは破棄できます。操作対象のドライブに対して開かれているファイルやディレクトリがあった場合、それらは全て無効になります。

-

この関数は、物理ドライブの状態に関わらず常に成功します。関数内では下位レイヤへのアクセスは発生せず、指定されたワーク・エリアをクリア(無効化)し、そのアドレスを内部配列に登録するだけです。単に登録済みのワーク・エリアをクリアする目的にも使えます。ボリュームへのアクセス開始のとき次のうちいずれかまたは両方の条件が真のとき、実際のマウント動作(物理ドライブの初期化、FATボリュームの検索、BPBに従いワーク・エリアを初期化)が行われます。

+

FatFsモジュールでは、それぞれの論理ドライブにファイル・システム・オブジェクトというワーク・エリアが必要です。この関数は論理ドライブにファイル・システム・オブジェクトを登録したり抹消したりします。何らかのファイル関数を使用する前に、この関数でその論理ドライブのファイル・システム・オブジェクトを与えておかなければなりません。fatfsにヌル・ポインタを指定すると、その論理ドライブのファイル・システム・オブジェクトの登録は抹消されるだけです。登録抹消されたファイル・システム・オブジェクトのメモリは解放できます。操作対象の論理ドライブ上に開かれているファイルやディレクトリがあった場合、それらは全て無効になります。この関数の内部処理は次のような順に行われます。

+
    +
  1. 対象の論理ドライブをpathから得る。
  2. +
  3. 既に登録されているファイル・システム・オブジェクトはクリアし、登録を解除する。
  4. +
  5. fatfsが有効なポインタのときは、そのファイル・システム・オブジェクトをクリアし登録する。
  6. +
  7. マウント動作が指定されているときは、それを実行する。
  8. +
+

optに0を指定すると、マウント動作(物理ドライブの初期化、FATボリュームの検索、BPBを解析しファイル・システム・オブジェクトを初期化)は行われず、関数は物理ドライブの状態に関わらず常に成功します。関数内では下位レイヤへのアクセスは発生せず、指定されたファイル・システム・オブジェクトをクリア(無効化)し、そのアドレスを内部配列に登録するだけです。単に登録済みのファイル・システム・オブジェクトをクリアする目的にも使えます。そして、続いてボリュームへのアクセスが行われたとき次のうちいずれかでも真の場合は、実際のマウント動作が行われます。

    -
  • ファイル・システム・オブジェクトが未初期化(f_mount()による)
  • -
  • 物理ドライブが未初期化(システム・リセットやメディアの取り外しによる)
  • +
  • ファイル・システム・オブジェクトがクリア(無効)状態(f_mount()の実行による)
  • +
  • 物理ドライブが未初期化状態(システム・リセットやメディアの取り外しによる)
-

下位レイヤがメディア交換の検出をサポートしないときは、アプリケーションはメディア交換のたびにf_mount()を実行する必要があります。

+

optに1を指定すると、登録に続いてマウント動作が行われます。マウントに失敗すると対応するエラーを返しますが、登録は有効なので続くボリュームへのアクセスで再びマウント動作が実行されます。

+

下位レイヤの実装上メディア交換の検出がサポートされない(disk_status()に反映されない)ときは、アプリケーションはメディア交換の後この関数でファイル・システム・オブジェクトを明示的にクリアして再マウントが正常に行えるようにする必要があります。

@@ -61,7 +74,7 @@ FRESULT f_mount (

参照

-

FATFS

+

f_open, FATFS

戻る

diff --git a/doc/ja/open.html b/doc/ja/open.html index d03eeb7..3cc7582 100644 --- a/doc/ja/open.html +++ b/doc/ja/open.html @@ -86,33 +86,64 @@ FRESULT f_open (
-

使用例(ファイル・コピー)

+

使用例

-void main (void)
+/* テキストファイルを読み出して表示 */
+
+FATFS FatFs;   /* 論理ドライブのワーク・エリア(ファイル・システム・オブジェクト) */
+
+int main (void)
 {
-    FATFS fs[2];         /* 論理ドライブのワーク・エリア(ファイル・システム・オブジェクト) */
+    FIL fil;       /* ファイル・オブジェクト */
+    char line[82]; /* 行バッファ */
+    FRESULT fr;    /* 戻り値 */
+
+
+    /* デフォルト・ドライブにワークエリアを与える */
+    f_mount(&FatFs, "", 0);
+
+    /* テキスト・ファイルを開く */
+    fr = f_open(&fil, "message.txt", FA_READ);
+    if (fr) return (int)fr;
+
+    /* 1行ずつ読み出して表示 */
+    while (f_gets(line, sizeof line, &fil))
+        printf(line);
+
+    /* ファイルを閉じる */
+    f_close(&fil);
+
+    return 0;
+}
+
+
+/* ドライブ1のファイル "file.bin" をドライブ0へコピー */
+
+int main (void)
+{
+    FATFS fs[2];         /* 論理ドライブのワークエリア(ファイル・システム・オブジェクト) */
     FIL fsrc, fdst;      /* ファイル・オブジェクト */
-    BYTE buffer[4096];   /* file copy buffer */
-    FRESULT res;         /* FatFs function common result code */
+    BYTE buffer[4096];   /* File copy buffer */
+    FRESULT fr;          /* FatFs function common result code */
     UINT br, bw;         /* File R/W count */
 
-    /* ドライブ0,1にワーク・エリアを与える (常に成功する) */
-    f_mount(0, &fs[0]);
-    f_mount(1, &fs[1]);
+    /* ドライブ0,1にワーク・エリアを与える */
+    f_mount(&fs[0], "0:", 0);
+    f_mount(&fs[1], "1:", 0);
 
-    /* ドライブ1のソース・ファイルを開く */
-    res = f_open(&fsrc, "1:srcfile.dat", FA_OPEN_EXISTING | FA_READ);
-    if (res) die(res);
+    /* ドライブ1のコピー元ファイルを開く */
+    res = f_open(&fsrc, "1:file.dat", FA_OPEN_EXISTING | FA_READ);
+    if (fr) return (int)fr;
 
-    /* ドライブ0にデスティネーション・ファイルを作成する */
-    res = f_open(&fdst, "0:dstfile.dat", FA_CREATE_ALWAYS | FA_WRITE);
-    if (res) die(res);
+    /* ドライブ0にコピー先ファイルを作成する */
+    res = f_open(&fdst, "0:file.dat", FA_CREATE_ALWAYS | FA_WRITE);
+    if (fr) return (int)fr;
 
-    /* ソースからデスティネーションにコピーする */
+    /* コピー元からコピー先にデータ転送する */
     for (;;) {
-        res = f_read(&fsrc, buffer, sizeof buffer, &br);
+        res = f_read(&fsrc, buffer, sizeof buffer, &br); /* コピー元からから読み出す */
         if (res || br == 0) break;   /* エラーかファイル終端 */
-        res = f_write(&fdst, buffer, br, &bw);
+        res = f_write(&fdst, buffer, br, &bw);           /* それをコピー先に書き込む */
         if (res || bw < br) break;   /* エラーかディスク満杯 */
     }
 
@@ -121,8 +152,10 @@ void main (void)
     f_close(&fdst);
 
     /* ワーク・エリアを開放する */
-    f_mount(0, NULL);
-    f_mount(1, NULL);
+    f_mount(NULL, "0:", 0);
+    f_mount(NULL, "1:", 0);
+
+    return (int)fr;
 }
 
diff --git a/doc/ja/opendir.html b/doc/ja/opendir.html index cdddec2..03c9331 100644 --- a/doc/ja/opendir.html +++ b/doc/ja/opendir.html @@ -16,7 +16,7 @@

ディレクトリを開きます。

 FRESULT f_opendir (
-  DIR* dj,           /* [OUT] ディレクトリ・ブジェクト構造体へのポインタ */
+  DIR* dp,           /* [OUT] ディレクトリ・ブジェクト構造体へのポインタ */
   const TCHAR* path  /* [IN] ディレクトリ名へのポインタ */
 );
 
@@ -25,8 +25,8 @@ FRESULT f_opendir (

引数

-
dj
-
初期化するディレクトリ・オブジェクト構造体へのポインタを指定します。
+
dp
+
空のディレクトリ・オブジェクト構造体へのポインタを指定します。
path
オープンするディレクトリのパス名を示すヌル文字'\0'終端の文字列へのポインタを指定します。
@@ -42,6 +42,7 @@ FRESULT f_opendir ( FR_NOT_READY, FR_NO_PATH, FR_INVALID_NAME, +FR_INVALID_OBJECT, FR_INVALID_DRIVE, FR_NOT_ENABLED, FR_NO_FILESYSTEM, @@ -53,7 +54,7 @@ FRESULT f_opendir (

解説

-

ディレクトリを開きます。正常終了したら、作成されたDIR構造体を使ってこのディレクトリの項目を順次読み出せます。作成されたディレクトリ・オブジェクトは、不要になったら任意の時点で破棄できます。

+

ディレクトリを開きます。正常終了したら、作成されたDIR構造体を使ってこのディレクトリの項目を順次読み出せます。

@@ -65,7 +66,7 @@ FRESULT f_opendir (

戻る

diff --git a/doc/ja/printf.html b/doc/ja/printf.html index 51c28a3..4fc37f7 100644 --- a/doc/ja/printf.html +++ b/doc/ja/printf.html @@ -45,7 +45,7 @@ int f_printf (

解説

-

この関数は、f_putc()およびf_puts()のラッパー関数です。書式制御機能はサブセットとなっていて、書式制御文字は次に示すものが使用可能です。

+

この関数は、f_putc()およびf_puts()のラッパー関数です。書式制御機能はC標準ライブラリのサブセットとなっていて、書式制御文字は次に示すものが使用可能です。

  • タイプ: c C s S d D u U x X b B
  • 精度指定: l L
  • @@ -57,7 +57,7 @@ int f_printf (

    対応情報

    _FS_READONLY == 0で、且つ_USE_STRFUNCが 1または 2のとき使用可能になります。2の時は、出力に含まれる'\n'"\r\n"に展開されてファイルに書き込まれます。

    -

    APIにUnicodeが選択されている(_LFN_UNICODEが1)ときは、UTF-8エンコードでファイルに書き込みます。それ以外の時は無変換(1文字1バイト)で書き込みます。

    +

    APIにUnicodeが選択(_LFN_UNICODEが1)されているときは、fmtはUnicode文字列になりますが、ファイル上のエンコードは、_STRF_ENCODEオプションで選択できます。それ以外の時は無変換(1バイト/1文字)で書き込みます。

    @@ -68,12 +68,12 @@ int f_printf ( f_printf(&fil, "%6d,%3d%%", -200, 5); /* " -200, 5%" */ f_printf(&fil, "%-6u", 100); /* "100 " */ f_printf(&fil, "%ld", 12345678L); /* "12345678" */ - f_printf(&fil, "%04x", 0xA3); /* "00a3" */ - f_printf(&fil, "%08LX", 0x123ABC); /* "00123ABC" */ + f_printf(&fil, "%04x", 0xAB); /* "00ab" */ + f_printf(&fil, "%08LX", 0x123ABCL); /* "00123ABC" */ f_printf(&fil, "%016b", 0x550F); /* "0101010100001111" */ f_printf(&fil, "%s", "String"); /* "String" */ - f_printf(&fil, "%-4s", "abc"); /* "abc " */ - f_printf(&fil, "%4s", "abc"); /* " abc" */ + f_printf(&fil, "%5s", "abc"); /* " abc" */ + f_printf(&fil, "%-5s", "abc"); /* "abc " */ f_printf(&fil, "%c", 'a'); /* "a" */ f_printf(&fil, "%f", 10.0); /* 浮動小数点は未サポート */ diff --git a/doc/ja/putc.html b/doc/ja/putc.html index b04babc..105992d 100644 --- a/doc/ja/putc.html +++ b/doc/ja/putc.html @@ -35,8 +35,8 @@ int f_putc (

    戻り値

    -

    文字が正常に書き込まれると書き込んだ文字数(1)が返されます。ディスクが満杯またはエラーにより書き込まれなかったときはEOF (-1)が返されます。

    -

    APIにUnicodeが選択されている(_LFN_UNICODEが1)ときは、UTF-8エンコードでファイルに書き込みます。それ以外の時は無変換(1文字1バイト)で書き込みます。

    +

    文字が正常に書き込まれると書き込んだ文字数が返されます。ディスクが満杯またはエラーにより書き込まれなかったときはEOF (-1)が返されます。

    +

    APIにUnicodeが選択(_LFN_UNICODEが1)されているときは、chrはUTF-16文字になりますが、ファイル上のエンコードは、_STRF_ENCODEオプションで選択できます。それ以外の時は無変換(1バイト/1文字)で書き込みます。

    diff --git a/doc/ja/puts.html b/doc/ja/puts.html index 9955796..62b76a6 100644 --- a/doc/ja/puts.html +++ b/doc/ja/puts.html @@ -36,13 +36,13 @@ int f_puts (

    戻り値

    文字列が正常に書き込まれると、書き込まれた文字数が返されます。ディスクが満杯またはエラーにより書き込みが中断されたときはEOF (-1)が返されます。

    -

    APIにUnicodeが選択されている(_LFN_UNICODEが1)ときは、UTF-8エンコードでファイルに書き込みます。それ以外の時は無変換(1文字1バイト)で書き込みます。

    +

    APIにUnicodeが選択(_LFN_UNICODEが1)されているときは、strはUTF-16文字列になりますが、ファイル上のエンコードは、_STRF_ENCODEオプションで選択できます。それ以外の時は無変換(1バイト/1文字)で書き込みます。

    解説

    -

    文字列をファイルに書き込みます。この関数はf_putc()のラッパー関数です。

    +

    文字列をファイルに書き込みます。この関数はf_write()のラッパー関数です。

    diff --git a/doc/ja/rc.html b/doc/ja/rc.html index 81fc996..f1c593a 100644 --- a/doc/ja/rc.html +++ b/doc/ja/rc.html @@ -53,7 +53,7 @@
    FR_WRITE_PROTECTED
    迚ゥ逅繝峨Λ繧、繝悶′譖ク縺崎セシ縺ソ遖∵ュ「迥カ諷九ョ縺ィ縺阪∵嶌縺崎セシ縺ソ邉サ縺ョ謫堺ス懊r陦後♀縺縺ィ縺励◆縲
    FR_INVALID_DRIVE
    -
    謖螳壹&繧後◆繝峨Λ繧、繝也分蜿キ縺檎┌蜉ケ縲(髢「騾」繧ェ繝励す繝ァ繝ウ: _VOLUMES)
    +
    繝代せ蜷阪〒謖螳壹&繧後◆繝峨Λ繧、繝也分蜿キ縺檎┌蜉ケ縲(髢「騾」繧ェ繝励す繝ァ繝ウ: _VOLUMES)
    FR_NOT_ENABLED
    縺昴ョ繝懊Μ繝・繝シ繝縺ョ謫堺ス懊↓蠢隕√↑繝ッ繝シ繧ッ繝サ繧ィ繝ェ繧「(繝輔ぃ繧、繝ォ繝サ繧キ繧ケ繝繝繝サ繧ェ繝悶ず繧ァ繧ッ繝域ァ矩菴)縺御ク弱∴繧峨l縺ヲ縺縺ェ縺縲
    FR_NO_FILESYSTEM
    diff --git a/doc/ja/readdir.html b/doc/ja/readdir.html index df04754..189617e 100644 --- a/doc/ja/readdir.html +++ b/doc/ja/readdir.html @@ -16,7 +16,7 @@

    ディレクトリ項目を読み出します

     FRESULT f_readdir (
    -  DIR* dj,      /* [IN] ディレクトリ・ブジェクト構造体へのポインタ */
    +  DIR* dp,      /* [IN] ディレクトリ・ブジェクト構造体へのポインタ */
       FILINFO* fno  /* [OUT] ファイル情報構造体へのポインタ */
     );
     
    @@ -25,7 +25,7 @@ FRESULT f_readdir (

    引数

    -
    dj
    +
    dp
    有効なディレクトリ・オブジェクト構造体へのポインタを指定します。
    fno
    読み出したディレクトリ項目を格納するファイル情報構造体へのポインタを指定します。
    @@ -49,14 +49,14 @@ FRESULT f_readdir (

    解説

    -

    ディレクトリの項目(ファイルとディレクトリ)を順次読み出します。この関数を繰り返し実行することによりそのディレクトリの全ての項目を読み出すことができます。全ての項目を読み出し、読み出す項目がもう無いときは、fname[]メンバにヌル文字列が返されます。ドット・エントリ("."、"..")は、相対パスが有効なとき(_FS_RPATH == 1)にのみ現れます。得られるファイル情報の詳細については FILINFO構造体を参照してください。fnoにヌル・ポインタを指定すると、そのディレクトリのリード・インデックスを巻き戻します。

    -

    LFN機能が有効な時は、f_readdir()関数の呼び出しに先立ってFILINFO構造体のlfnamelfsizeが有効な値で初期化されていなければなりません。lfnameはLFNを格納するバッファで、lfsizeはそのバッファの要素数です。次の条件に一つでも該当する場合は、LFN格納バッファにヌル文字列が返されます。

    +

    ディレクトリの項目(ファイルとディレクトリ)を順次読み出します。この関数を繰り返し実行することによりそのディレクトリの全ての項目を読み出すことができます。全ての項目が読み出され、読み出す項目がもう無いときは、fname[]メンバにヌル文字列が返されます。ドット・エントリ("."、"..")は、相対パスが有効なとき(_FS_RPATH >= 1)にのみ現れます。得られるファイル情報の詳細については FILINFO構造体を参照してください。fnoにヌル・ポインタを指定すると、そのディレクトリのリード・インデックスを先頭に巻き戻します。

    +

    LFN機能が有効な時は、f_readdir()関数の呼び出しに先立ってFILINFO構造体のlfnamelfsizeが有効な値で初期化されていなければなりません。lfnameはLFNを格納するバッファで、lfsizeはそのバッファの要素数です。LFNを読み出す必要がないときは、lfnameにヌル・ポインタをセットしてください。次の条件に一つでも該当する場合は、LFN格納バッファにヌル文字列が返されます。

      -
    • そのディレクトリ項目にLFNが存在しない。
    • +
    • ディレクトリ項目にLFN情報が存在しない。
    • LFNの長さに対してLFN格納バッファまたはLFN操作バッファのサイズが不十分。
    • -
    • LFNに現在のOEMコードに存在しない文字が含まれている。(Unicode APIではないとき)
    • +
    • LFNに現在のOEMコードに存在しない文字が含まれている。(非Unicode構成のとき)
    -

    また、lfnameにヌル・ポインタを指定した場合は、LFNに関して何も返されません。LFNが存在しないときは、fname[]メンバのSFNにASCII英小文字が含まれる場合があります。

    +

    また、ディレクトリ項目にLFN情報が存在しない場合は、fname[]に英小文字が含まれる場合があります。

    @@ -106,6 +106,7 @@ FRESULT scan_files ( printf("%s/%s\n", path, fn); } } + f_closedir(&dir); } return res; @@ -116,7 +117,7 @@ FRESULT scan_files (

    戻る

    diff --git a/doc/ja/rename.html b/doc/ja/rename.html index 70bf5b7..403daf5 100644 --- a/doc/ja/rename.html +++ b/doc/ja/rename.html @@ -13,7 +13,7 @@

    f_rename

    -

    オブジェクトの名前の変更または移動。

    +

    ファイルまたはサブ・ディレクトリの名前の変更または移動。

     FRESULT f_rename (
       const TCHAR* old_name, /* [IN] 古いオブジェクト名 */
    @@ -26,7 +26,7 @@ FRESULT f_rename (
     

    引数

    old_name
    -
    変更対象のオブジェクト(ファイルまたはディレクトリ)のパス名を示すヌル文字'\0'終端の文字列へのポインタを指定します。
    +
    変更対象のオブジェクトのパス名を示すヌル文字'\0'終端の文字列へのポインタを指定します。
    new_name
    新しいオブジェクトのパス名を示すヌル文字'\0'終端の文字列へのポインタを指定します。既に存在する名前は使えません。また、ドライブ番号は指定できず、old_nameで指定された論理ドライブ上のオブジェクトとして扱われます。
    @@ -56,7 +56,7 @@ FRESULT f_rename (

    解説

    -

    オブジェクトの名前を変更します。また、同時に別のディレクトリへの移動も可能です。開かれているオブジェクトに対して使用してはなりません

    +

    ファイルまたはサブ・ディレクトリの名前を変更します。また、同時に別のディレクトリへの移動も可能です。開かれているオブジェクトに対して使用してはなりません

    diff --git a/doc/ja/sdir.html b/doc/ja/sdir.html index 3039057..246c48f 100644 --- a/doc/ja/sdir.html +++ b/doc/ja/sdir.html @@ -18,15 +18,18 @@ typedef struct { FATFS* fs; /* 親ファイル・システム・オブジェクトへのポインタ */ WORD id; /* 親ファイル・システム・オブジェクトのマウントID */ - WORD index; /* 次に読み出すディレクトリ・インデックス番号 */ - DWORD sclust; /* ディレクトリ開始クラスタ (0:ルート) */ + WORD index; /* 次に検索開始するディレクトリ・インデックス番号 */ + DWORD sclust; /* テーブル開始クラスタ (0:ルート) */ DWORD clust; /* 現在のクラスタ番号 */ DWORD sect; /* 現在のセクタ番号 */ BYTE* dir; /* 現在のSFNエントリへのポインタ */ BYTE* fn; /* SFNバッファへのポインタ (in/out) {file[8],ext[3],status[1]} */ +#if _FS_LOCK + UINT lockid; /* ロックID */ +#endif #if _USE_LFN WCHAR* lfn; /* LFNバッファへのポインタ */ - WORD lfn_idx; /* 最後にマッチしたLFNエントリのインデックス (0xFFFF:無効) */ + WORD lfn_idx; /* 最後にマッチしたLFNエントリの先頭インデックス (0xFFFF:無効) */ #endif } DIR;
    diff --git a/doc/ja/sfatfs.html b/doc/ja/sfatfs.html index b8f2bf1..afd5382 100644 --- a/doc/ja/sfatfs.html +++ b/doc/ja/sfatfs.html @@ -19,10 +19,10 @@ typedef struct { BYTE fs_type; /* FATタイプ */ BYTE drv; /* 物理ドライブ番号 */ - BYTE csize; /* クラスタ当たりのセクタ数 */ - BYTE n_fats; /* FATの多重化数 */ + BYTE csize; /* クラスタ当たりのセクタ数 (1,2,4,8,...,128)*/ + BYTE n_fats; /* FATの多重化数 (1,2) */ BYTE wflag; /* win[]ダーティ・フラグ */ - BYTE fsi_flag; /* fsinfoダーティ・フラグ */ + BYTE fsi_flag; /* FSINFOフラグ (b7:Disabled, b0:Dirty)*/ WORD id; /* ファイル・システム・マウントID */ WORD n_rootdir; /* ルート・ディレクトリのエントリ数 (FAT12/16) */ #if _MAX_SS != 512 @@ -32,18 +32,17 @@ _SYNC_t sobj; /* 同期オブジェクトID */ #endif #if !_FS_READONLY - DWORD last_clust; /* 最後に割り当てられたクラスタ番号 */ - DWORD free_clust; /* 空きクラスタ数 */ - DWORD fsi_sector; /* fsinfoセクタ (FAT32) */ + DWORD last_clust; /* FSINFO: 最後に割り当てられたクラスタ番号 */ + DWORD free_clust; /* FSINFO: 空きクラスタ数 */ #endif #if _FS_RPATH DWORD cdir; /* カレント・ディレクトリのクラスタ (0:ルート) */ #endif - DWORD n_fatent; /* FATのエントリ数 (== クラスタ数 + 2) */ - DWORD fsize; /* FAT 1個当たりのセクタ数 */ + DWORD n_fatent; /* FATエントリ数 (総クラスタ数 + 2) */ + DWORD fsize; /* FAT 1個のセクタ数 */ DWORD volbase; /* ボリューム開始セクタ */ DWORD fatbase; /* FAT領域開始セクタ */ - DWORD dirbase; /* ルート・ディレクトリ開始セクタ/クラスタ */ + DWORD dirbase; /* ルート・ディレクトリ領域開始セクタ(クラスタ) */ DWORD database; /* データ領域開始セクタ */ DWORD winsect; /* win[]に現れているセクタ番号 */ BYTE win[_MAX_SS]; /* ディスク・アクセス・ウィンドウ */ diff --git a/doc/ja/sfile.html b/doc/ja/sfile.html index e4c9dcf..2129044 100644 --- a/doc/ja/sfile.html +++ b/doc/ja/sfile.html @@ -20,24 +20,24 @@ FATFS* fs; /* 親ファイル・システム・オブジェクトへのポインタ */ WORD id; /* 親ファイル・システム・オブジェクトのマウントID */ BYTE flag; /* ファイル・ステータス・フラグ */ - BYTE pad1; + BYTE err; /* エラー中断フラグ */ DWORD fptr; /* ファイル読み書きポインタ (ファイル先頭からのバイト・オフセット) */ DWORD fsize; /* ファイル・サイズ(バイト単位) */ - DWORD sclust; /* ファイル開始クラスタ番号 (set 0 if fsize==0) */ + DWORD sclust; /* ファイル開始クラスタ番号 (0:割り当て無し) */ DWORD clust; /* 現在のクラスタ */ DWORD dsect; /* 現在のデータ・セクタ */ -#if _FS_READONLY == 0 +#if !_FS_READONLY DWORD dir_sect; /* このファイルのディレクトリ・エントリのあるセクタ */ BYTE* dir_ptr; /* このファイルのディレクトリへのポインタ */ #endif #if _USE_FASTSEEK - DWORD* cltbl; /* ファイルのクラスタ・リンク情報へのポインタ (Nulled on file open) */ + DWORD* cltbl; /* ファイルのクラスタ・リンク情報へのポインタ (オープン時にNULLがセットされる) */ #endif -#if _FS_SHARE +#if _FS_LOCK UINT lockid; /* ファイル・ロックID */ #endif #if !_FS_TINY - BYTE buf[_MAX_SS]; /* データ転送バッファ */ + BYTE buf[_MAX_SS]; /* ファイル・プライベート・データ転送バッファ */ #endif } FIL; diff --git a/doc/ja/sfileinfo.html b/doc/ja/sfileinfo.html index aac7927..a4b1fe2 100644 --- a/doc/ja/sfileinfo.html +++ b/doc/ja/sfileinfo.html @@ -62,7 +62,7 @@
    lfname
    返される長いファイル名を格納するバッファへのポインタ。この構造体を使用する前にアプリケーションにより初期化されなければなりません。このメンバにNULLが設定されるとLFNは返されません。非LFN構成のときはこのメンバは存在しません。
    lfsize
    -
    長いファイル名を格納するバッファのサイズ(文字数)。この構造体を使用する前にアプリケーションにより初期化されなければなりません。非LFN構成のときはこのメンバは存在しません。
    +
    長いファイル名を格納するバッファのサイズ(要素数)。この構造体を使用する前にアプリケーションにより初期化されなければなりません。非LFN構成のときはこのメンバは存在しません。

    戻る

    diff --git a/doc/ja/stat.html b/doc/ja/stat.html index 5ab92bd..cfc7ce1 100644 --- a/doc/ja/stat.html +++ b/doc/ja/stat.html @@ -13,9 +13,10 @@

    f_stat

    +

    ファイルまたはサブ・ディレクトリの存在を調べ、またその情報を取得します。

     FRESULT f_stat (
    -  const TCHAR* path,  /* [IN] ファイルまたはディレクトリ名へのポインタ */
    +  const TCHAR* path,  /* [IN] オブジェクト名へのポインタ */
       FILINFO* fno        /* [OUT] ファイル情報構造体へのポインタ */
     );
     
    @@ -25,9 +26,9 @@ FRESULT f_stat (

    引数

    path
    -
    情報を得るファイルまたはディレクトリ名を示すヌル文字'\0'終端の文字列を指すポインタを指定します。
    +
    チェックするオブジェクト名を示すヌル文字'\0'終端の文字列を指すポインタを指定します。
    fno
    -
    読み出したファイル情報を格納するファイル情報構造体へのポインタを指定します。
    +
    オブジェクトが存在したときにその情報を格納するファイル情報構造体へのポインタを指定します。この情報が不要なときはヌル・ポインタを指定してください。
    @@ -53,7 +54,7 @@ FRESULT f_stat (

    解説

    -

    指定されたファイルまたはディレクトリに関する情報(サイズ、タイムスタンプおよび属性)を得ます。ディレクトリのサイズ情報は無効で常に0です。

    +

    指定されたファイルまたはサブ・ディレクトリの存在を調べ、それ関する情報(サイズ、タイムスタンプおよび属性)を得ます。存在する場合はFR_OKが帰り、ファイル情報構造体にその情報がストアされます。存在しない場合は、FR_NO_FILEが帰ります。

    diff --git a/doc/ja/sync.html b/doc/ja/sync.html index 681186d..f5c42b5 100644 --- a/doc/ja/sync.html +++ b/doc/ja/sync.html @@ -45,7 +45,8 @@ FRESULT f_sync (

    解説

    -

    この関数はf_close()と同じ処理を実行しますが、ファイルは引き続き開かれたままになり、読み書きを続行できます。ロギングなど、書き込みモードで長時間ファイルが開かれているアプリケーションにおいて、定期的または区切りの良いところでこの関数を使用することにより、不意の電源断やメディアの取り外しにより失われるデータを最小にすることができます。実際のところ、f_close()内ではこの関数を呼び出した後ファイル・オブジェクトを無効化しているだけなので、f_close()直前のf_sync()は意味がありません。

    +

    この関数はf_close()と同じ処理を実行しますが、ファイルは引き続き開かれたままになり、読み書きを続行できます。ロギングなど、書き込みモードで長時間ファイルが開かれているアプリケーションにおいて、定期的または区切りの良いところでこの関数を使用することにより、不意の電源断やメディアの取り外しにより失われるデータを最小にすることができます。この背景については、アプリケーション・ノートも参照してください。

    +

    実際のところ、f_close()内ではこの関数を呼び出した後ファイル・オブジェクトを無効化しているだけなので、f_close()直前のf_sync()は意味がありません。

    diff --git a/doc/ja/unlink.html b/doc/ja/unlink.html index 92763a5..347599e 100644 --- a/doc/ja/unlink.html +++ b/doc/ja/unlink.html @@ -13,7 +13,7 @@

    f_unlink

    -

    ファイルまたはディレクトリを削除します。

    +

    ファイルまたはサブ・ディレクトリを削除します。

     FRESULT f_unlink (
       const TCHAR* path  /* [IN] オブジェクト名へのポインタ */
    @@ -54,11 +54,11 @@ FRESULT f_unlink (
     
     

    解説

    -

    削除対象のオブジェクが次の条件に当てはまる場合、そのアクセスは拒否され関数は失敗します。 +

    削除対象のオブジェクトが次の条件に当てはまる場合、そのアクセスは拒否(FR_DENIEDまたはFR_LOCKED)され関数は失敗します。

    • リード・オンリー属性(AM_RDO)を持っている。
    • -
    • 空でないディレクトリまたはカレント・ディレクトリ。
    • -
    • 開かれているファイル。多重アクセス制御が有効なときは安全に拒否されますが、そうでないときは不正な操作となり、FAT構造が破壊される可能性があります。
    • +
    • 空でないサブ・ディレクトリまたはカレント・ディレクトリ。
    • +
    • 開かれているファイルまたはサブ・ディレクトリ。多重アクセス制御が有効なときは安全に拒否されますが、そうでないときは不正な操作となり、FAT構造が破壊される可能性があります。

    diff --git a/doc/ja/utime.html b/doc/ja/utime.html index c412e57..8bccf65 100644 --- a/doc/ja/utime.html +++ b/doc/ja/utime.html @@ -13,7 +13,7 @@

    f_utime

    -

    オブジェクトのタイムスタンプを変更します。

    +

    ファイルまたはサブ・ディレクトリのタイムスタンプを変更します。

     FRESULT f_utime (
       const TCHAR* path,  /* [IN] オブジェクト名へのポインタ */
    @@ -26,7 +26,7 @@ FRESULT f_utime (
     

    引数

    path
    -
    変更対象のファイルまたはディレクトリのパス名を示すヌル文字'\0'終端の文字列を指定します。
    +
    変更対象のオブジェクトのパス名を示すヌル文字'\0'終端の文字列を指定します。
    fno
    設定する日付と時間をfdateftimeメンバに設定されたFILINFO構造体へのポインタ。他のメンバはこの関数では意味を持ちません。
    diff --git a/doc/updates.txt b/doc/updates.txt index e773558..066d65a 100644 --- a/doc/updates.txt +++ b/doc/updates.txt @@ -1,3 +1,14 @@ +R0.10, Oct 02,'13 + Added selection of character encoding on the file. (_STRF_ENCODE) + Added f_closedir(). + Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO) + Added forced mount feature with changes of f_mount(). + Improved behavior of volume auto detection. + Improved write throughput of f_puts() and f_printf(). + Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write(). + Fixed f_write() can be truncated when the file size is close to 4GB. + Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect error code. + R0.09b, Jan 24, 2013 Added f_getlabel() and f_setlabel(). (_USE_LABEL = 1) diff --git a/src/00readme.txt b/src/00readme.txt index f7330e9..dba47db 100644 --- a/src/00readme.txt +++ b/src/00readme.txt @@ -1,4 +1,4 @@ -FatFs Module Source Files R0.09b (C)ChaN, 2013 +FatFs Module Source Files R0.10 (C)ChaN, 2013 FILES @@ -24,7 +24,7 @@ AGREEMENTS small embedded systems. This is a free software and is opened for education, research and commercial developments under license policy of following trems. - Copyright (C) 2012, ChaN, all right reserved. + Copyright (C) 2013, ChaN, all right reserved. * The FatFs module is a free software and there is NO WARRANTY. * No restriction on use. You can use, modify and redistribute it for @@ -136,3 +136,12 @@ REVISION HISTORY Jan 23,'13 R0.09b Added f_getlabel() and f_setlabel(). (_USE_LABEL == 1) + Oct 02,'13 R0.10 Added selection of character encoding on the file. (_STRF_ENCODE) + Added f_closedir(). + Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO) + Added forced mount feature with changes of f_mount(). + Improved behavior of volume auto detection. + Improved write throughput of f_puts() and f_printf(). + Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write(). + Fixed f_write() can be truncated when the file size is close to 4GB. + Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect error code. diff --git a/src/diskio.c b/src/diskio.c index cce6ee7..461e99a 100644 --- a/src/diskio.c +++ b/src/diskio.c @@ -102,7 +102,7 @@ DRESULT disk_read ( BYTE pdrv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ - BYTE count /* Number of sectors to read (1..128) */ + UINT count /* Number of sectors to read (1..128) */ ) { DRESULT res; @@ -150,7 +150,7 @@ DRESULT disk_write ( BYTE pdrv, /* Physical drive nmuber (0..) */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ - BYTE count /* Number of sectors to write (1..128) */ + UINT count /* Number of sectors to write (1..128) */ ) { DRESULT res; diff --git a/src/diskio.h b/src/diskio.h index 580fbf7..6d4a28b 100644 --- a/src/diskio.h +++ b/src/diskio.h @@ -34,8 +34,8 @@ typedef enum { DSTATUS disk_initialize (BYTE pdrv); DSTATUS disk_status (BYTE pdrv); -DRESULT disk_read (BYTE pdrv, BYTE*buff, DWORD sector, BYTE count); -DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, BYTE count); +DRESULT disk_read (BYTE pdrv, BYTE*buff, DWORD sector, UINT count); +DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff); diff --git a/src/ff.c b/src/ff.c index 7c9857c..4306822 100644 --- a/src/ff.c +++ b/src/ff.c @@ -1,5 +1,5 @@ /*----------------------------------------------------------------------------/ -/ FatFs - FAT file system module R0.09b (C)ChaN, 2013 +/ FatFs - FAT file system module R0.10 (C)ChaN, 2013 /-----------------------------------------------------------------------------/ / FatFs module is a generic FAT file system module for small embedded systems. / This is a free software that opened for education, research and commercial @@ -36,12 +36,12 @@ / Added minimization level 3. / Fixed an endian sensitive code in f_mkfs(). / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG. -/ Added FSInfo support. +/ Added FSINFO support. / Fixed DBCS name can result FR_INVALID_NAME. / Fixed short seek (<= csize) collapses the file object. / / Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs(). -/ Fixed f_mkfs() on FAT32 creates incorrect FSInfo. +/ Fixed f_mkfs() on FAT32 creates incorrect FSINFO. / Fixed f_mkdir() on FAT32 creates incorrect directory. / Feb 03,'08 R0.05a Added f_truncate() and f_utime(). / Fixed off by one error at FAT sub-type determination. @@ -65,10 +65,10 @@ / Fixed wrong cache control in f_lseek(). / Added relative path feature. / Added f_chdir() and f_chdrive(). -/ Added proper case conversion to extended char. +/ Added proper case conversion to extended character. / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h. -/ Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH. -/ Fixed name matching error on the 13 char boundary. +/ Fixed f_unlink() fails to remove a sub-directory on _FS_RPATH. +/ Fixed name matching error on the 13 character boundary. / Added a configuration option, _LFN_UNICODE. / Changed f_readdir() to return the SFN with always upper case on non-LFN cfg. / @@ -76,28 +76,38 @@ / Added file lock feature. (_FS_SHARE) / Added fast seek feature. (_USE_FASTSEEK) / Changed some types on the API, XCHAR->TCHAR. -/ Changed fname member in the FILINFO structure on Unicode cfg. +/ Changed .fname in the FILINFO structure on Unicode cfg. / String functions support UTF-8 encoding files on Unicode cfg. -/ Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2) +/ Aug 16,'10 R0.08a Added f_getcwd(). / Added sector erase feature. (_USE_ERASE) / Moved file lock semaphore table from fs object to the bss. / Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'. / Fixed f_mkfs() creates wrong FAT32 volume. / Jan 15,'11 R0.08b Fast seek feature is also applied to f_read() and f_write(). / f_lseek() reports required table size on creating CLMP. -/ Extended format syntax of f_printf function. +/ Extended format syntax of f_printf(). / Ignores duplicated directory separators in given path name. / -/ Sep 06,'11 R0.09 f_mkfs() supports multiple partition to finish the multiple partition feature. -/ Added f_fdisk(). (_MULTI_PARTITION = 2) -/ Aug 27,'12 R0.09a Fixed assertion failure due to OS/2 EA on FAT12/16 volume. -/ Changed f_open() and f_opendir reject null object pointer to avoid crash. +/ Sep 06,'11 R0.09 f_mkfs() supports multiple partition to complete the multiple partition feature. +/ Added f_fdisk(). +/ Aug 27,'12 R0.09a Changed f_open() and f_opendir() reject null object pointer to avoid crash. / Changed option name _FS_SHARE to _FS_LOCK. -/ Jan 24,'13 R0.09b Added f_setlabel() and f_getlabel(). (_USE_LABEL = 1) +/ Fixed assertion failure due to OS/2 EA on FAT12/16 volume. +/ Jan 24,'13 R0.09b Added f_setlabel() and f_getlabel(). +/ +/ Oct 02,'13 R0.10 Added selection of character encoding on the file. (_STRF_ENCODE) +/ Added f_closedir(). +/ Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO) +/ Added forced mount feature with changes of f_mount(). +/ Improved behavior of volume auto detection. +/ Improved write throughput of f_puts() and f_printf(). +/ Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write(). +/ Fixed f_write() can be truncated when the file size is close to 4GB. +/ Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect error code. /---------------------------------------------------------------------------*/ -#include "ff.h" /* FatFs configurations and declarations */ -#include "diskio.h" /* Declarations of low level disk I/O functions */ +#include "ff.h" /* Declarations of FatFs API */ +#include "diskio.h" /* Declarations of disk I/O functions */ /*-------------------------------------------------------------------------- @@ -106,7 +116,7 @@ ---------------------------------------------------------------------------*/ -#if _FATFS != 82786 /* Revision ID */ +#if _FATFS != 80960 /* Revision ID */ #error Wrong include file (ff.h). #endif @@ -125,7 +135,7 @@ /* Reentrancy related */ #if _FS_REENTRANT #if _USE_LFN == 1 -#error Static LFN work area must not be used in re-entrant configuration. +#error Static LFN work area cannot be used at thread-safe configuration. #endif #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; } #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; } @@ -134,25 +144,25 @@ #define LEAVE_FF(fs, res) return res #endif -#define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); } +#define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); } /* File access control feature */ #if _FS_LOCK #if _FS_READONLY -#error _FS_LOCK must be 0 on read-only cfg. +#error _FS_LOCK must be 0 at read-only cfg. #endif typedef struct { - FATFS *fs; /* File ID 1, volume (NULL:blank entry) */ - DWORD clu; /* File ID 2, directory */ - WORD idx; /* File ID 3, directory index */ - WORD ctr; /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */ + FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */ + DWORD clu; /* Object ID 2, directory */ + WORD idx; /* Object ID 3, directory index */ + WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */ } FILESEM; #endif -/* DBCS code ranges and SBCS extend char conversion table */ +/* DBCS code ranges and SBCS extend character conversion table */ #if _CODE_PAGE == 932 /* Japanese Shift-JIS */ #define _DF1S 0x81 /* DBC 1st byte range 1 start */ @@ -387,9 +397,8 @@ typedef struct { /* FAT sub-type boundaries */ -/* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */ -#define MIN_FAT16 4086 /* Minimum number of clusters for FAT16 */ -#define MIN_FAT32 65526 /* Minimum number of clusters for FAT32 */ +#define MIN_FAT16 4086U /* Minimum number of clusters for FAT16 */ +#define MIN_FAT32 65526U /* Minimum number of clusters for FAT32 */ /* FatFs refers the members in the FAT structures as byte array instead of @@ -402,7 +411,7 @@ typedef struct { #define BPB_SecPerClus 13 /* Cluster size [sector] (1) */ #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (2) */ #define BPB_NumFATs 16 /* Number of FAT copies (1) */ -#define BPB_RootEntCnt 17 /* Number of root dir entries for FAT12/16 (2) */ +#define BPB_RootEntCnt 17 /* Number of root directory entries for FAT12/16 (2) */ #define BPB_TotSec16 19 /* Volume size [sector] (2) */ #define BPB_Media 21 /* Media descriptor (1) */ #define BPB_FATSz16 22 /* FAT size [sector] (2) */ @@ -418,8 +427,8 @@ typedef struct { #define BPB_FATSz32 36 /* FAT size [sector] (4) */ #define BPB_ExtFlags 40 /* Extended flags (2) */ #define BPB_FSVer 42 /* File system version (2) */ -#define BPB_RootClus 44 /* Root dir first cluster (4) */ -#define BPB_FSInfo 48 /* Offset of FSInfo sector (2) */ +#define BPB_RootClus 44 /* Root directory first cluster (4) */ +#define BPB_FSInfo 48 /* Offset of FSINFO sector (2) */ #define BPB_BkBootSec 50 /* Offset of backup boot sector (2) */ #define BS_DrvNum32 64 /* Physical drive number (2) */ #define BS_BootSig32 66 /* Extended boot signature (1) */ @@ -475,14 +484,14 @@ FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) * static WORD Fsid; /* File system mount ID */ -#if _FS_RPATH +#if _FS_RPATH && _VOLUMES >= 2 static BYTE CurrVol; /* Current drive */ #endif #if _FS_LOCK static -FILESEM Files[_FS_LOCK]; /* File lock semaphores */ +FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */ #endif #if _USE_LFN == 0 /* No LFN feature */ @@ -491,7 +500,8 @@ FILESEM Files[_FS_LOCK]; /* File lock semaphores */ #define FREE_BUF() #elif _USE_LFN == 1 /* LFN feature with static working buffer */ -static WCHAR LfnBuf[_MAX_LFN+1]; +static +WCHAR LfnBuf[_MAX_LFN+1]; #define DEF_NAMEBUF BYTE sfn[12] #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = LfnBuf; } #define FREE_BUF() @@ -515,7 +525,7 @@ static WCHAR LfnBuf[_MAX_LFN+1]; #ifdef _EXCVT static -const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for extended chars */ +const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for extended characters */ #endif @@ -579,14 +589,14 @@ int chk_chr (const char* str, int chr) { + /*-----------------------------------------------------------------------*/ /* Request/Release grant to access the volume */ /*-----------------------------------------------------------------------*/ #if _FS_REENTRANT - static int lock_fs ( - FATFS *fs /* File system object */ + FATFS* fs /* File system object */ ) { return ff_req_grant(fs->sobj); @@ -595,7 +605,7 @@ int lock_fs ( static void unlock_fs ( - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ FRESULT res /* Result code to be returned */ ) { @@ -611,6 +621,7 @@ void unlock_fs ( + /*-----------------------------------------------------------------------*/ /* File lock control functions */ /*-----------------------------------------------------------------------*/ @@ -618,7 +629,7 @@ void unlock_fs ( static FRESULT chk_lock ( /* Check if the file can be accessed */ - DIR* dj, /* Directory object pointing the file to be checked */ + DIR* dp, /* Directory object pointing the file to be checked */ int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */ ) { @@ -627,23 +638,23 @@ FRESULT chk_lock ( /* Check if the file can be accessed */ /* Search file semaphore table */ for (i = be = 0; i < _FS_LOCK; i++) { if (Files[i].fs) { /* Existing entry */ - if (Files[i].fs == dj->fs && /* Check if the file matched with an open file */ - Files[i].clu == dj->sclust && - Files[i].idx == dj->index) break; + if (Files[i].fs == dp->fs && /* Check if the object matched with an open object */ + Files[i].clu == dp->sclust && + Files[i].idx == dp->index) break; } else { /* Blank entry */ - be++; + be = 1; } } - if (i == _FS_LOCK) /* The file is not opened */ - return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new file? */ + if (i == _FS_LOCK) /* The object is not opened */ + return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */ - /* The file has been opened. Reject any open against writing file and all write mode open */ + /* The object has been opened. Reject any open against writing file and all write mode open */ return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK; } static -int enq_lock (void) /* Check if an entry is available for a new file */ +int enq_lock (void) /* Check if an entry is available for a new object */ { UINT i; @@ -653,26 +664,26 @@ int enq_lock (void) /* Check if an entry is available for a new file */ static -UINT inc_lock ( /* Increment file open counter and returns its index (0:int error) */ - DIR* dj, /* Directory object pointing the file to register or increment */ - int acc /* Desired access mode (0:Read, !0:Write) */ +UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */ + DIR* dp, /* Directory object pointing the file to register or increment */ + int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */ ) { UINT i; - for (i = 0; i < _FS_LOCK; i++) { /* Find the file */ - if (Files[i].fs == dj->fs && - Files[i].clu == dj->sclust && - Files[i].idx == dj->index) break; + for (i = 0; i < _FS_LOCK; i++) { /* Find the object */ + if (Files[i].fs == dp->fs && + Files[i].clu == dp->sclust && + Files[i].idx == dp->index) break; } if (i == _FS_LOCK) { /* Not opened. Register it as new. */ for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ; - if (i == _FS_LOCK) return 0; /* No space to register (int err) */ - Files[i].fs = dj->fs; - Files[i].clu = dj->sclust; - Files[i].idx = dj->index; + if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */ + Files[i].fs = dp->fs; + Files[i].clu = dp->sclust; + Files[i].idx = dp->index; Files[i].ctr = 0; } @@ -685,23 +696,23 @@ UINT inc_lock ( /* Increment file open counter and returns its index (0:int erro static -FRESULT dec_lock ( /* Decrement file open counter */ - UINT i /* Semaphore index */ +FRESULT dec_lock ( /* Decrement object open counter */ + UINT i /* Semaphore index (1..) */ ) { WORD n; FRESULT res; - if (--i < _FS_LOCK) { + if (--i < _FS_LOCK) { /* Shift index number origin from 0 */ n = Files[i].ctr; - if (n == 0x100) n = 0; - if (n) n--; + if (n == 0x100) n = 0; /* If write mode open, delete the entry */ + if (n) n--; /* Decrement read mode open count */ Files[i].ctr = n; - if (!n) Files[i].fs = 0; + if (!n) Files[i].fs = 0; /* Delete the entry if open count gets zero */ res = FR_OK; } else { - res = FR_INT_ERR; + res = FR_INT_ERR; /* Invalid index nunber */ } return res; } @@ -722,27 +733,26 @@ void clear_lock ( /* Clear lock entries of the volume */ -/*-----------------------------------------------------------------------*/ -/* Move/Flush disk access window */ -/*-----------------------------------------------------------------------*/ - +/*-----------------------------------------------------------------------*/ +/* Move/Flush disk access window in the file system object */ +/*-----------------------------------------------------------------------*/ #if !_FS_READONLY static FRESULT sync_window ( - FATFS *fs /* File system object */ + FATFS* fs /* File system object */ ) { DWORD wsect; UINT nf; - + if (fs->wflag) { /* Write back the sector if it is dirty */ wsect = fs->winsect; /* Current sector number */ - if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) + if (disk_write(fs->drv, fs->win, wsect, 1)) return FR_DISK_ERR; fs->wflag = 0; - if (wsect >= fs->fatbase && wsect < (fs->fatbase + fs->fsize)) { /* In FAT area? */ + if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */ for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */ wsect += fs->fsize; disk_write(fs->drv, fs->win, wsect, 1); @@ -756,7 +766,7 @@ FRESULT sync_window ( static FRESULT move_window ( - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ DWORD sector /* Sector number to make appearance in the fs->win[] */ ) { @@ -765,7 +775,7 @@ FRESULT move_window ( if (sync_window(fs) != FR_OK) return FR_DISK_ERR; #endif - if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) + if (disk_read(fs->drv, fs->win, sector, 1)) return FR_DISK_ERR; fs->winsect = sector; } @@ -782,7 +792,7 @@ FRESULT move_window ( #if !_FS_READONLY static FRESULT sync_fs ( /* FR_OK: successful, FR_DISK_ERR: failed */ - FATFS *fs /* File system object */ + FATFS* fs /* File system object */ ) { FRESULT res; @@ -790,18 +800,18 @@ FRESULT sync_fs ( /* FR_OK: successful, FR_DISK_ERR: failed */ res = sync_window(fs); if (res == FR_OK) { - /* Update FSInfo sector if needed */ - if (fs->fs_type == FS_FAT32 && fs->fsi_flag) { - fs->winsect = 0; - /* Create FSInfo structure */ - mem_set(fs->win, 0, 512); + /* Update FSINFO sector if needed */ + if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) { + /* Create FSINFO structure */ + mem_set(fs->win, 0, SS(fs)); ST_WORD(fs->win+BS_55AA, 0xAA55); ST_DWORD(fs->win+FSI_LeadSig, 0x41615252); ST_DWORD(fs->win+FSI_StrucSig, 0x61417272); ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust); ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust); - /* Write it into the FSInfo sector */ - disk_write(fs->drv, fs->win, fs->fsi_sector, 1); + /* Write it into the FSINFO sector */ + fs->winsect = fs->volbase + 1; + disk_write(fs->drv, fs->win, fs->winsect, 1); fs->fsi_flag = 0; } /* Make sure that no pending write process in the physical drive */ @@ -822,7 +832,7 @@ FRESULT sync_fs ( /* FR_OK: successful, FR_DISK_ERR: failed */ DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */ - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ DWORD clst /* Cluster# to be converted */ ) { @@ -840,7 +850,7 @@ DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */ DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status */ - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ DWORD clst /* Cluster# to get the link information */ ) { @@ -858,7 +868,7 @@ DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status wc = fs->win[bc % SS(fs)]; bc++; if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break; wc |= fs->win[bc % SS(fs)] << 8; - return (clst & 1) ? (wc >> 4) : (wc & 0xFFF); + return clst & 1 ? wc >> 4 : (wc & 0xFFF); case FS_FAT16 : if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)))) break; @@ -883,7 +893,7 @@ DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status #if !_FS_READONLY FRESULT put_fat ( - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ DWORD clst, /* Cluster# to be changed in range of 2 to fs->n_fatent - 1 */ DWORD val /* New value to mark the cluster */ ) @@ -946,7 +956,7 @@ FRESULT put_fat ( #if !_FS_READONLY static FRESULT remove_chain ( - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ DWORD clst /* Cluster# to remove a chain from */ ) { @@ -968,9 +978,9 @@ FRESULT remove_chain ( if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */ res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */ if (res != FR_OK) break; - if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */ + if (fs->free_clust != 0xFFFFFFFF) { /* Update FSINFO */ fs->free_clust++; - fs->fsi_flag = 1; + fs->fsi_flag |= 1; } #if _USE_ERASE if (ecl + 1 == nxt) { /* Is next cluster contiguous? */ @@ -999,7 +1009,7 @@ FRESULT remove_chain ( #if !_FS_READONLY static DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */ - FATFS *fs, /* File system object */ + FATFS* fs, /* File system object */ DWORD clst /* Cluster# to stretch. 0 means create a new chain. */ ) { @@ -1040,7 +1050,7 @@ DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk err fs->last_clust = ncl; /* Update FSINFO */ if (fs->free_clust != 0xFFFFFFFF) { fs->free_clust--; - fs->fsi_flag = 1; + fs->fsi_flag |= 1; } } else { ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; @@ -1052,6 +1062,7 @@ DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk err + /*-----------------------------------------------------------------------*/ /* FAT handling - Convert offset into cluster with link map table */ /*-----------------------------------------------------------------------*/ @@ -1080,13 +1091,14 @@ DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */ + /*-----------------------------------------------------------------------*/ /* Directory handling - Set directory index */ /*-----------------------------------------------------------------------*/ static FRESULT dir_sdi ( - DIR *dj, /* Pointer to directory object */ + DIR* dp, /* Pointer to directory object */ WORD idx /* Index of directory table */ ) { @@ -1094,33 +1106,33 @@ FRESULT dir_sdi ( WORD ic; - dj->index = idx; - clst = dj->sclust; - if (clst == 1 || clst >= dj->fs->n_fatent) /* Check start cluster range */ + dp->index = idx; + clst = dp->sclust; + if (clst == 1 || clst >= dp->fs->n_fatent) /* Check start cluster range */ return FR_INT_ERR; - if (!clst && dj->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */ - clst = dj->fs->dirbase; + if (!clst && dp->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */ + clst = dp->fs->dirbase; - if (clst == 0) { /* Static table (root-dir in FAT12/16) */ - dj->clust = clst; - if (idx >= dj->fs->n_rootdir) /* Index is out of range */ + if (clst == 0) { /* Static table (root-directory in FAT12/16) */ + dp->clust = clst; + if (idx >= dp->fs->n_rootdir) /* Index is out of range */ return FR_INT_ERR; - dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / SZ_DIR); /* Sector# */ + dp->sect = dp->fs->dirbase + idx / (SS(dp->fs) / SZ_DIR); /* Sector# */ } - else { /* Dynamic table (sub-dirs or root-dir in FAT32) */ - ic = SS(dj->fs) / SZ_DIR * dj->fs->csize; /* Entries per cluster */ + else { /* Dynamic table (sub-dirs or root-directory in FAT32) */ + ic = SS(dp->fs) / SZ_DIR * dp->fs->csize; /* Entries per cluster */ while (idx >= ic) { /* Follow cluster chain */ - clst = get_fat(dj->fs, clst); /* Get next cluster */ + clst = get_fat(dp->fs, clst); /* Get next cluster */ if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */ - if (clst < 2 || clst >= dj->fs->n_fatent) /* Reached to end of table or int error */ + if (clst < 2 || clst >= dp->fs->n_fatent) /* Reached to end of table or int error */ return FR_INT_ERR; idx -= ic; } - dj->clust = clst; - dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / SZ_DIR); /* Sector# */ + dp->clust = clst; + dp->sect = clust2sect(dp->fs, clst) + idx / (SS(dp->fs) / SZ_DIR); /* Sector# */ } - dj->dir = dj->fs->win + (idx % (SS(dj->fs) / SZ_DIR)) * SZ_DIR; /* Ptr to the entry in the sector */ + dp->dir = dp->fs->win + (idx % (SS(dp->fs) / SZ_DIR)) * SZ_DIR; /* Ptr to the entry in the sector */ return FR_OK; /* Seek succeeded */ } @@ -1134,7 +1146,7 @@ FRESULT dir_sdi ( static FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */ - DIR *dj, /* Pointer to the directory object */ + DIR* dp, /* Pointer to the directory object */ int stretch /* 0: Do not stretch table, 1: Stretch table if needed */ ) { @@ -1142,53 +1154,53 @@ FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:Could WORD i; - stretch = stretch; /* To suppress warning on read-only cfg. */ - i = dj->index + 1; - if (!i || !dj->sect) /* Report EOT when index has reached 65535 */ + i = dp->index + 1; + if (!i || !dp->sect) /* Report EOT when index has reached 65535 */ return FR_NO_FILE; - if (!(i % (SS(dj->fs) / SZ_DIR))) { /* Sector changed? */ - dj->sect++; /* Next sector */ + if (!(i % (SS(dp->fs) / SZ_DIR))) { /* Sector changed? */ + dp->sect++; /* Next sector */ - if (dj->clust == 0) { /* Static table */ - if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */ + if (!dp->clust) { /* Static table */ + if (i >= dp->fs->n_rootdir) /* Report EOT if it reached end of static table */ return FR_NO_FILE; } else { /* Dynamic table */ - if (((i / (SS(dj->fs) / SZ_DIR)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */ - clst = get_fat(dj->fs, dj->clust); /* Get next cluster */ + if (((i / (SS(dp->fs) / SZ_DIR)) & (dp->fs->csize - 1)) == 0) { /* Cluster changed? */ + clst = get_fat(dp->fs, dp->clust); /* Get next cluster */ if (clst <= 1) return FR_INT_ERR; if (clst == 0xFFFFFFFF) return FR_DISK_ERR; - if (clst >= dj->fs->n_fatent) { /* When it reached end of dynamic table */ + if (clst >= dp->fs->n_fatent) { /* If it reached end of dynamic table, */ #if !_FS_READONLY BYTE c; - if (!stretch) return FR_NO_FILE; /* When do not stretch, report EOT */ - clst = create_chain(dj->fs, dj->clust); /* Stretch cluster chain */ + if (!stretch) return FR_NO_FILE; /* If do not stretch, report EOT */ + clst = create_chain(dp->fs, dp->clust); /* Stretch cluster chain */ if (clst == 0) return FR_DENIED; /* No free cluster */ if (clst == 1) return FR_INT_ERR; if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Clean-up stretched table */ - if (sync_window(dj->fs)) return FR_DISK_ERR; /* Flush active window */ - mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */ - dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */ - for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */ - dj->fs->wflag = 1; - if (sync_window(dj->fs)) return FR_DISK_ERR; - dj->fs->winsect++; + if (sync_window(dp->fs)) return FR_DISK_ERR;/* Flush disk access window */ + mem_set(dp->fs->win, 0, SS(dp->fs)); /* Clear window buffer */ + dp->fs->winsect = clust2sect(dp->fs, clst); /* Cluster start sector */ + for (c = 0; c < dp->fs->csize; c++) { /* Fill the new cluster with 0 */ + dp->fs->wflag = 1; + if (sync_window(dp->fs)) return FR_DISK_ERR; + dp->fs->winsect++; } - dj->fs->winsect -= c; /* Rewind window address */ + dp->fs->winsect -= c; /* Rewind window offset */ #else - return FR_NO_FILE; /* Report EOT */ + if (!stretch) return FR_NO_FILE; /* If do not stretch, report EOT */ + return FR_NO_FILE; /* Report EOT */ #endif } - dj->clust = clst; /* Initialize data for new cluster */ - dj->sect = clust2sect(dj->fs, clst); + dp->clust = clst; /* Initialize data for new cluster */ + dp->sect = clust2sect(dp->fs, clst); } } } - dj->index = i; - dj->dir = dj->fs->win + (i % (SS(dj->fs) / SZ_DIR)) * SZ_DIR; + dp->index = i; /* Current index */ + dp->dir = dp->fs->win + (i % (SS(dp->fs) / SZ_DIR)) * SZ_DIR; /* Current entry in the window */ return FR_OK; } @@ -1203,7 +1215,7 @@ FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:Could #if !_FS_READONLY static FRESULT dir_alloc ( - DIR* dj, /* Pointer to the directory object */ + DIR* dp, /* Pointer to the directory object */ UINT nent /* Number of contiguous entries to allocate (1-21) */ ) { @@ -1211,34 +1223,36 @@ FRESULT dir_alloc ( UINT n; - res = dir_sdi(dj, 0); + res = dir_sdi(dp, 0); if (res == FR_OK) { n = 0; do { - res = move_window(dj->fs, dj->sect); + res = move_window(dp->fs, dp->sect); if (res != FR_OK) break; - if (dj->dir[0] == DDE || dj->dir[0] == 0) { /* Is it a blank entry? */ - if (++n == nent) break; /* A block of contiguous entry is found */ + if (dp->dir[0] == DDE || dp->dir[0] == 0) { /* Is it a blank entry? */ + if (++n == nent) break; /* A block of contiguous entries is found */ } else { n = 0; /* Not a blank entry. Restart to search */ } - res = dir_next(dj, 1); /* Next entry with table stretch enabled */ + res = dir_next(dp, 1); /* Next entry with table stretch enabled */ } while (res == FR_OK); } + if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */ return res; } #endif + /*-----------------------------------------------------------------------*/ /* Directory handling - Load/Store start cluster number */ /*-----------------------------------------------------------------------*/ static DWORD ld_clust ( - FATFS *fs, /* Pointer to the fs object */ - BYTE *dir /* Pointer to the directory entry */ + FATFS* fs, /* Pointer to the fs object */ + BYTE* dir /* Pointer to the directory entry */ ) { DWORD cl; @@ -1254,7 +1268,7 @@ DWORD ld_clust ( #if !_FS_READONLY static void st_clust ( - BYTE *dir, /* Pointer to the directory entry */ + BYTE* dir, /* Pointer to the directory entry */ DWORD cl /* Value to be set */ ) { @@ -1265,18 +1279,19 @@ void st_clust ( + /*-----------------------------------------------------------------------*/ /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */ /*-----------------------------------------------------------------------*/ #if _USE_LFN static -const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */ +const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */ static int cmp_lfn ( /* 1:Matched, 0:Not matched */ - WCHAR *lfnbuf, /* Pointer to the LFN to be compared */ - BYTE *dir /* Pointer to the directory entry containing a part of LFN */ + WCHAR* lfnbuf, /* Pointer to the LFN to be compared */ + BYTE* dir /* Pointer to the directory entry containing a part of LFN */ ) { UINT i, s; @@ -1287,14 +1302,14 @@ int cmp_lfn ( /* 1:Matched, 0:Not matched */ s = 0; wc = 1; do { uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */ - if (wc) { /* Last char has not been processed */ + if (wc) { /* Last character has not been processed */ wc = ff_wtoupper(uc); /* Convert it to upper case */ if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it */ return 0; /* Not matched */ } else { if (uc != 0xFFFF) return 0; /* Check filler */ } - } while (++s < 13); /* Repeat until all chars in the entry are checked */ + } while (++s < 13); /* Repeat until all characters in the entry are checked */ if ((dir[LDIR_Ord] & LLE) && wc && lfnbuf[i]) /* Last segment matched but different length */ return 0; @@ -1306,8 +1321,8 @@ int cmp_lfn ( /* 1:Matched, 0:Not matched */ static int pick_lfn ( /* 1:Succeeded, 0:Buffer overflow */ - WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */ - BYTE *dir /* Pointer to the directory entry */ + WCHAR* lfnbuf, /* Pointer to the Unicode-LFN buffer */ + BYTE* dir /* Pointer to the directory entry */ ) { UINT i, s; @@ -1319,7 +1334,7 @@ int pick_lfn ( /* 1:Succeeded, 0:Buffer overflow */ s = 0; wc = 1; do { uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */ - if (wc) { /* Last char has not been processed */ + if (wc) { /* Last character has not been processed */ if (i >= _MAX_LFN) return 0; /* Buffer overflow? */ lfnbuf[i++] = wc = uc; /* Store it */ } else { @@ -1339,8 +1354,8 @@ int pick_lfn ( /* 1:Succeeded, 0:Buffer overflow */ #if !_FS_READONLY static void fit_lfn ( - const WCHAR *lfnbuf, /* Pointer to the LFN buffer */ - BYTE *dir, /* Pointer to the directory entry */ + const WCHAR* lfnbuf, /* Pointer to the LFN buffer */ + BYTE* dir, /* Pointer to the directory entry */ BYTE ord, /* LFN order (1-20) */ BYTE sum /* SFN sum */ ) @@ -1357,9 +1372,9 @@ void fit_lfn ( i = (ord - 1) * 13; /* Get offset in the LFN buffer */ s = wc = 0; do { - if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective char */ + if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective character */ ST_WORD(dir+LfnOfs[s], wc); /* Put it */ - if (!wc) wc = 0xFFFF; /* Padding chars following last char */ + if (!wc) wc = 0xFFFF; /* Padding characters following last character */ } while (++s < 13); if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLE; /* Bottom LFN part is the start of LFN sequence */ dir[LDIR_Ord] = ord; /* Set the LFN order */ @@ -1370,14 +1385,15 @@ void fit_lfn ( + /*-----------------------------------------------------------------------*/ /* Create numbered name */ /*-----------------------------------------------------------------------*/ #if _USE_LFN void gen_numname ( - BYTE *dst, /* Pointer to generated SFN */ - const BYTE *src, /* Pointer to source SFN to be modified */ - const WCHAR *lfn, /* Pointer to LFN */ + BYTE* dst, /* Pointer to generated SFN */ + const BYTE* src, /* Pointer to source SFN to be modified */ + const WCHAR* lfn, /* Pointer to LFN */ WORD seq /* Sequence number */ ) { @@ -1423,7 +1439,7 @@ void gen_numname ( #if _USE_LFN static BYTE sum_sfn ( - const BYTE *dir /* Ptr to directory entry */ + const BYTE* dir /* Pointer to the SFN entry */ ) { BYTE sum = 0; @@ -1443,7 +1459,7 @@ BYTE sum_sfn ( static FRESULT dir_find ( - DIR *dj /* Pointer to the directory object linked to the file name */ + DIR* dp /* Pointer to the directory object linked to the file name */ ) { FRESULT res; @@ -1452,16 +1468,16 @@ FRESULT dir_find ( BYTE a, ord, sum; #endif - res = dir_sdi(dj, 0); /* Rewind directory object */ + res = dir_sdi(dp, 0); /* Rewind directory object */ if (res != FR_OK) return res; #if _USE_LFN ord = sum = 0xFF; #endif do { - res = move_window(dj->fs, dj->sect); + res = move_window(dp->fs, dp->sect); if (res != FR_OK) break; - dir = dj->dir; /* Ptr to the directory entry of current index */ + dir = dp->dir; /* Ptr to the directory entry of current index */ c = dir[DIR_Name]; if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ #if _USE_LFN /* LFN configuration */ @@ -1470,26 +1486,26 @@ FRESULT dir_find ( ord = 0xFF; } else { if (a == AM_LFN) { /* An LFN entry is found */ - if (dj->lfn) { + if (dp->lfn) { if (c & LLE) { /* Is it start of LFN sequence? */ sum = dir[LDIR_Chksum]; c &= ~LLE; ord = c; /* LFN start order */ - dj->lfn_idx = dj->index; + dp->lfn_idx = dp->index; } /* Check validity of the LFN entry and compare it with given name */ - ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF; + ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dp->lfn, dir)) ? ord - 1 : 0xFF; } } else { /* An SFN entry is found */ if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */ - ord = 0xFF; dj->lfn_idx = 0xFFFF; /* Reset LFN sequence */ - if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break; /* SFN matched? */ + ord = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */ + if (!(dp->fn[NS] & NS_LOSS) && !mem_cmp(dir, dp->fn, 11)) break; /* SFN matched? */ } } #else /* Non LFN configuration */ - if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */ + if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dp->fn, 11)) /* Is it a valid entry? */ break; #endif - res = dir_next(dj, 0); /* Next entry */ + res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK); return res; @@ -1504,8 +1520,8 @@ FRESULT dir_find ( #if _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 static FRESULT dir_read ( - DIR *dj, /* Pointer to the directory object */ - int vol /* Filtered by 0:file/dir or 1:volume label */ + DIR* dp, /* Pointer to the directory object */ + int vol /* Filtered by 0:file/directory or 1:volume label */ ) { FRESULT res; @@ -1515,40 +1531,40 @@ FRESULT dir_read ( #endif res = FR_NO_FILE; - while (dj->sect) { - res = move_window(dj->fs, dj->sect); + while (dp->sect) { + res = move_window(dp->fs, dp->sect); if (res != FR_OK) break; - dir = dj->dir; /* Ptr to the directory entry of current index */ + dir = dp->dir; /* Ptr to the directory entry of current index */ c = dir[DIR_Name]; if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ a = dir[DIR_Attr] & AM_MASK; #if _USE_LFN /* LFN configuration */ - if (c == DDE || (!_FS_RPATH && c == '.') || (a == AM_VOL) != vol) { /* An entry without valid data */ + if (c == DDE || (!_FS_RPATH && c == '.') || (int)(a == AM_VOL) != vol) { /* An entry without valid data */ ord = 0xFF; } else { if (a == AM_LFN) { /* An LFN entry is found */ if (c & LLE) { /* Is it start of LFN sequence? */ sum = dir[LDIR_Chksum]; c &= ~LLE; ord = c; - dj->lfn_idx = dj->index; + dp->lfn_idx = dp->index; } /* Check LFN validity and capture it */ - ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF; + ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dp->lfn, dir)) ? ord - 1 : 0xFF; } else { /* An SFN entry is found */ if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */ - dj->lfn_idx = 0xFFFF; /* It has no LFN. */ + dp->lfn_idx = 0xFFFF; /* It has no LFN. */ break; } } #else /* Non LFN configuration */ - if (c != DDE && (_FS_RPATH || c != '.') && a != AM_LFN && (a == AM_VOL) == vol) /* Is it a valid entry? */ + if (c != DDE && (_FS_RPATH || c != '.') && a != AM_LFN && (int)(a == AM_VOL) == vol) /* Is it a valid entry? */ break; #endif - res = dir_next(dj, 0); /* Next entry */ + res = dir_next(dp, 0); /* Next entry */ if (res != FR_OK) break; } - if (res != FR_OK) dj->sect = 0; + if (res != FR_OK) dp->sect = 0; return res; } @@ -1556,13 +1572,14 @@ FRESULT dir_read ( + /*-----------------------------------------------------------------------*/ /* Register an object to the directory */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY static FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */ - DIR *dj /* Target directory with object name to be created */ + DIR* dp /* Target directory with object name to be created */ ) { FRESULT res; @@ -1572,22 +1589,22 @@ FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many WCHAR *lfn; - fn = dj->fn; lfn = dj->lfn; + fn = dp->fn; lfn = dp->lfn; mem_cpy(sn, fn, 12); if (_FS_RPATH && (sn[NS] & NS_DOT)) /* Cannot create dot entry */ return FR_INVALID_NAME; if (sn[NS] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */ - fn[NS] = 0; dj->lfn = 0; /* Find only SFN */ + fn[NS] = 0; dp->lfn = 0; /* Find only SFN */ for (n = 1; n < 100; n++) { gen_numname(fn, sn, lfn, n); /* Generate a numbered name */ - res = dir_find(dj); /* Check if the name collides with existing SFN */ + res = dir_find(dp); /* Check if the name collides with existing SFN */ if (res != FR_OK) break; } if (n == 100) return FR_DENIED; /* Abort if too many collisions */ if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */ - fn[NS] = sn[NS]; dj->lfn = lfn; + fn[NS] = sn[NS]; dp->lfn = lfn; } if (sn[NS] & NS_LFN) { /* When LFN is to be created, allocate entries for an SFN + LFNs. */ @@ -1596,34 +1613,34 @@ FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many } else { /* Otherwise allocate an entry for an SFN */ ne = 1; } - res = dir_alloc(dj, ne); /* Allocate entries */ + res = dir_alloc(dp, ne); /* Allocate entries */ if (res == FR_OK && --ne) { /* Set LFN entry if needed */ - res = dir_sdi(dj, (WORD)(dj->index - ne)); + res = dir_sdi(dp, (WORD)(dp->index - ne)); if (res == FR_OK) { - sum = sum_sfn(dj->fn); /* Sum value of the SFN tied to the LFN */ + sum = sum_sfn(dp->fn); /* Sum value of the SFN tied to the LFN */ do { /* Store LFN entries in bottom first */ - res = move_window(dj->fs, dj->sect); + res = move_window(dp->fs, dp->sect); if (res != FR_OK) break; - fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum); - dj->fs->wflag = 1; - res = dir_next(dj, 0); /* Next entry */ + fit_lfn(dp->lfn, dp->dir, (BYTE)ne, sum); + dp->fs->wflag = 1; + res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK && --ne); } } #else /* Non LFN configuration */ - res = dir_alloc(dj, 1); /* Allocate an entry for SFN */ + res = dir_alloc(dp, 1); /* Allocate an entry for SFN */ #endif if (res == FR_OK) { /* Set SFN entry */ - res = move_window(dj->fs, dj->sect); + res = move_window(dp->fs, dp->sect); if (res == FR_OK) { - mem_set(dj->dir, 0, SZ_DIR); /* Clean the entry */ - mem_cpy(dj->dir, dj->fn, 11); /* Put SFN */ + mem_set(dp->dir, 0, SZ_DIR); /* Clean the entry */ + mem_cpy(dp->dir, dp->fn, 11); /* Put SFN */ #if _USE_LFN - dj->dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT); /* Put NT flag */ + dp->dir[DIR_NTres] = dp->fn[NS] & (NS_BODY | NS_EXT); /* Put NT flag */ #endif - dj->fs->wflag = 1; + dp->fs->wflag = 1; } } @@ -1640,34 +1657,34 @@ FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many #if !_FS_READONLY && !_FS_MINIMIZE static FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */ - DIR *dj /* Directory object pointing the entry to be removed */ + DIR* dp /* Directory object pointing the entry to be removed */ ) { FRESULT res; #if _USE_LFN /* LFN configuration */ WORD i; - i = dj->index; /* SFN index */ - res = dir_sdi(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx)); /* Goto the SFN or top of the LFN entries */ + i = dp->index; /* SFN index */ + res = dir_sdi(dp, (WORD)((dp->lfn_idx == 0xFFFF) ? i : dp->lfn_idx)); /* Goto the SFN or top of the LFN entries */ if (res == FR_OK) { do { - res = move_window(dj->fs, dj->sect); + res = move_window(dp->fs, dp->sect); if (res != FR_OK) break; - *dj->dir = DDE; /* Mark the entry "deleted" */ - dj->fs->wflag = 1; - if (dj->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */ - res = dir_next(dj, 0); /* Next entry */ + *dp->dir = DDE; /* Mark the entry "deleted" */ + dp->fs->wflag = 1; + if (dp->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */ + res = dir_next(dp, 0); /* Next entry */ } while (res == FR_OK); if (res == FR_NO_FILE) res = FR_INT_ERR; } #else /* Non LFN configuration */ - res = dir_sdi(dj, dj->index); + res = dir_sdi(dp, dp->index); if (res == FR_OK) { - res = move_window(dj->fs, dj->sect); + res = move_window(dp->fs, dp->sect); if (res == FR_OK) { - *dj->dir = DDE; /* Mark the entry "deleted" */ - dj->fs->wflag = 1; + *dp->dir = DDE; /* Mark the entry "deleted" */ + dp->fs->wflag = 1; } } #endif @@ -1685,8 +1702,8 @@ FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */ static FRESULT create_name ( - DIR *dj, /* Pointer to the directory object */ - const TCHAR **path /* Pointer to pointer to the segment in the path string */ + DIR* dp, /* Pointer to the directory object */ + const TCHAR** path /* Pointer to pointer to the segment in the path string */ ) { #if _USE_LFN /* LFN configuration */ @@ -1697,7 +1714,7 @@ FRESULT create_name ( /* Create LFN in Unicode */ for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */ - lfn = dj->lfn; + lfn = dp->lfn; si = di = 0; for (;;) { w = p[si++]; /* Get a character */ @@ -1715,9 +1732,9 @@ FRESULT create_name ( w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */ if (!w) return FR_INVALID_NAME; /* Reject invalid code */ #endif - if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */ + if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal characters for LFN */ return FR_INVALID_NAME; - lfn[di++] = w; /* Store the Unicode char */ + lfn[di++] = w; /* Store the Unicode character */ } *path = &p[si]; /* Return pointer to the next segment */ cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */ @@ -1726,8 +1743,8 @@ FRESULT create_name ( (di == 2 && lfn[di-1] == '.' && lfn[di-2] == '.')) { lfn[di] = 0; for (i = 0; i < 11; i++) - dj->fn[i] = (i < di) ? '.' : ' '; - dj->fn[i] = cf | NS_DOT; /* This is a dot entry */ + dp->fn[i] = (i < di) ? '.' : ' '; + dp->fn[i] = cf | NS_DOT; /* This is a dot entry */ return FR_OK; } #endif @@ -1741,14 +1758,14 @@ FRESULT create_name ( lfn[di] = 0; /* LFN is created */ /* Create SFN in directory form */ - mem_set(dj->fn, ' ', 11); + mem_set(dp->fn, ' ', 11); for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */ if (si) cf |= NS_LOSS | NS_LFN; while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */ b = i = 0; ni = 8; for (;;) { - w = lfn[si++]; /* Get an LFN char */ + w = lfn[si++]; /* Get an LFN character */ if (!w) break; /* Break on end of the LFN */ if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */ cf |= NS_LOSS | NS_LFN; continue; @@ -1764,23 +1781,23 @@ FRESULT create_name ( b <<= 2; continue; } - if (w >= 0x80) { /* Non ASCII char */ + if (w >= 0x80) { /* Non ASCII character */ #ifdef _EXCVT w = ff_convert(w, 0); /* Unicode -> OEM code */ - if (w) w = ExCvt[w - 0x80]; /* Convert extended char to upper (SBCS) */ + if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */ #else w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */ #endif cf |= NS_LFN; /* Force create LFN entry */ } - if (_DF1S && w >= 0x100) { /* Double byte char (always false on SBCS cfg) */ + if (_DF1S && w >= 0x100) { /* Double byte character (always false on SBCS cfg) */ if (i >= ni - 1) { cf |= NS_LOSS | NS_LFN; i = ni; continue; } - dj->fn[i++] = (BYTE)(w >> 8); - } else { /* Single byte char */ - if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal chars for SFN */ + dp->fn[i++] = (BYTE)(w >> 8); + } else { /* Single byte character */ + if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */ w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */ } else { if (IsUpper(w)) { /* ASCII large capital */ @@ -1792,20 +1809,20 @@ FRESULT create_name ( } } } - dj->fn[i++] = (BYTE)w; + dp->fn[i++] = (BYTE)w; } - if (dj->fn[0] == DDE) dj->fn[0] = NDDE; /* If the first char collides with deleted mark, replace it with 0x05 */ + if (dp->fn[0] == DDE) dp->fn[0] = NDDE; /* If the first character collides with deleted mark, replace it with 0x05 */ if (ni == 8) b <<= 2; if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */ cf |= NS_LFN; - if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended char, NT flags are created */ + if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */ if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */ if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */ } - dj->fn[NS] = cf; /* SFN is created */ + dp->fn[NS] = cf; /* SFN is created */ return FR_OK; @@ -1817,7 +1834,7 @@ FRESULT create_name ( /* Create file name in directory form */ for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */ - sfn = dj->fn; + sfn = dp->fn; mem_set(sfn, ' ', 11); si = i = b = 0; ni = 8; #if _FS_RPATH @@ -1841,13 +1858,13 @@ FRESULT create_name ( i = 8; ni = 11; b <<= 2; continue; } - if (c >= 0x80) { /* Extended char? */ + if (c >= 0x80) { /* Extended character? */ b |= 3; /* Eliminate NT flag */ #ifdef _EXCVT - c = ExCvt[c - 0x80]; /* To upper extended chars (SBCS cfg) */ + c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */ #else #if !_DF1S - return FR_INVALID_NAME; /* Reject extended chars (ASCII cfg) */ + return FR_INVALID_NAME; /* Reject extended characters (ASCII cfg) */ #endif #endif } @@ -1874,7 +1891,7 @@ FRESULT create_name ( c = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */ if (!i) return FR_INVALID_NAME; /* Reject nul string */ - if (sfn[0] == DDE) sfn[0] = NDDE; /* When first char collides with DDE, replace it with 0x05 */ + if (sfn[0] == DDE) sfn[0] = NDDE; /* When first character collides with DDE, replace it with 0x05 */ if (ni == 8) b <<= 2; if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Name extension has only small capital) */ @@ -1895,74 +1912,62 @@ FRESULT create_name ( #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 static void get_fileinfo ( /* No return code */ - DIR *dj, /* Pointer to the directory object */ - FILINFO *fno /* Pointer to the file information to be filled */ + DIR* dp, /* Pointer to the directory object */ + FILINFO* fno /* Pointer to the file information to be filled */ ) { UINT i; - BYTE nt, *dir; TCHAR *p, c; p = fno->fname; - if (dj->sect) { - dir = dj->dir; - nt = dir[DIR_NTres]; /* NT flag */ - for (i = 0; i < 8; i++) { /* Copy name body */ - c = dir[i]; - if (c == ' ') break; - if (c == NDDE) c = (TCHAR)DDE; - if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20; + if (dp->sect) { /* Get SFN */ + BYTE *dir = dp->dir; + + i = 0; + while (i < 11) { /* Copy name body and extension */ + c = (TCHAR)dir[i++]; + if (c == ' ') continue; /* Skip padding spaces */ + if (c == NDDE) c = (TCHAR)DDE; /* Restore replaced DDE character */ + if (i == 9) *p++ = '.'; /* Insert a . if extension is exist */ +#if _USE_LFN + if (IsUpper(c) && (dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY))) + c += 0x20; /* To lower */ #if _LFN_UNICODE - if (IsDBCS1(c) && i < 7 && IsDBCS2(dir[i+1])) - c = (c << 8) | dir[++i]; - c = ff_convert(c, 1); + if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dir[i])) + c = c << 8 | dir[i++]; + c = ff_convert(c, 1); /* OEM -> Unicode */ if (!c) c = '?'; #endif - *p++ = c; - } - if (dir[8] != ' ') { /* Copy name extension */ - *p++ = '.'; - for (i = 8; i < 11; i++) { - c = dir[i]; - if (c == ' ') break; - if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20; -#if _LFN_UNICODE - if (IsDBCS1(c) && i < 10 && IsDBCS2(dir[i+1])) - c = (c << 8) | dir[++i]; - c = ff_convert(c, 1); - if (!c) c = '?'; #endif - *p++ = c; - } + *p++ = c; } fno->fattrib = dir[DIR_Attr]; /* Attribute */ fno->fsize = LD_DWORD(dir+DIR_FileSize); /* Size */ fno->fdate = LD_WORD(dir+DIR_WrtDate); /* Date */ fno->ftime = LD_WORD(dir+DIR_WrtTime); /* Time */ } - *p = 0; /* Terminate SFN str by a \0 */ + *p = 0; /* Terminate SFN string by a \0 */ #if _USE_LFN - if (fno->lfname && fno->lfsize) { - TCHAR *tp = fno->lfname; + if (fno->lfname) { WCHAR w, *lfn; - i = 0; - if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */ - lfn = dj->lfn; - while ((w = *lfn++) != 0) { /* Get an LFN char */ + i = 0; p = fno->lfname; + if (dp->sect && fno->lfsize && dp->lfn_idx != 0xFFFF) { /* Get LFN if available */ + lfn = dp->lfn; + while ((w = *lfn++) != 0) { /* Get an LFN character */ #if !_LFN_UNICODE - w = ff_convert(w, 0); /* Unicode -> OEM conversion */ - if (!w) { i = 0; break; } /* Could not convert, no LFN */ - if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */ - tp[i++] = (TCHAR)(w >> 8); + w = ff_convert(w, 0); /* Unicode -> OEM */ + if (!w) { i = 0; break; } /* No LFN if it could not be converted */ + if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */ + p[i++] = (TCHAR)(w >> 8); #endif - if (i >= fno->lfsize - 1) { i = 0; break; } /* Buffer overflow, no LFN */ - tp[i++] = (TCHAR)w; + if (i >= fno->lfsize - 1) { i = 0; break; } /* No LFN if buffer overflow */ + p[i++] = (TCHAR)w; } } - tp[i] = 0; /* Terminate the LFN str by a \0 */ + p[i] = 0; /* Terminate LFN string by a \0 */ } #endif } @@ -1971,14 +1976,46 @@ void get_fileinfo ( /* No return code */ +/*-----------------------------------------------------------------------*/ +/* Get logical drive number from path name */ +/*-----------------------------------------------------------------------*/ + +static +int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */ + const TCHAR** path /* Pointer to pointer to the path name */ +) +{ + int vol = -1; + + + if (*path) { + vol = (*path)[0] - '0'; + if ((UINT)vol < 9 && (*path)[1] == ':') { /* There is a drive number */ + *path += 2; /* Get value and strip it */ + if (vol >= _VOLUMES) vol = -1; /* Check if the drive number is valid */ + } else { /* No drive number use default drive */ +#if _FS_RPATH && _VOLUMES >= 2 + vol = CurrVol; /* Current drive */ +#else + vol = 0; /* Drive 0 */ +#endif + } + } + + return vol; +} + + + + /*-----------------------------------------------------------------------*/ /* Follow a file path */ /*-----------------------------------------------------------------------*/ static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ - DIR *dj, /* Directory object to return last directory and found object */ - const TCHAR *path /* Full-path string to find a file or directory */ + DIR* dp, /* Directory object to return last directory and found object */ + const TCHAR* path /* Full-path string to find a file or directory */ ) { FRESULT res; @@ -1986,44 +2023,44 @@ FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ #if _FS_RPATH - if (*path == '/' || *path == '\\') { /* There is a heading separator */ - path++; dj->sclust = 0; /* Strip it and start from the root dir */ - } else { /* No heading separator */ - dj->sclust = dj->fs->cdir; /* Start from the current dir */ + if (*path == '/' || *path == '\\') { /* There is a heading separator */ + path++; dp->sclust = 0; /* Strip it and start from the root directory */ + } else { /* No heading separator */ + dp->sclust = dp->fs->cdir; /* Start from the current directory */ } #else - if (*path == '/' || *path == '\\') /* Strip heading separator if exist */ + if (*path == '/' || *path == '\\') /* Strip heading separator if exist */ path++; - dj->sclust = 0; /* Start from the root dir */ + dp->sclust = 0; /* Always start from the root directory */ #endif - if ((UINT)*path < ' ') { /* Nul path means the start directory itself */ - res = dir_sdi(dj, 0); - dj->dir = 0; - } else { /* Follow path */ + if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */ + res = dir_sdi(dp, 0); + dp->dir = 0; + } else { /* Follow path */ for (;;) { - res = create_name(dj, &path); /* Get a segment */ + res = create_name(dp, &path); /* Get a segment name of the path */ if (res != FR_OK) break; - res = dir_find(dj); /* Find it */ - ns = *(dj->fn+NS); + res = dir_find(dp); /* Find an object with the sagment name */ + ns = dp->fn[NS]; if (res != FR_OK) { /* Failed to find the object */ - if (res != FR_NO_FILE) break; /* Abort if any hard error occurred */ - /* Object not found */ - if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exit */ - dj->sclust = 0; dj->dir = 0; /* It is the root dir */ - res = FR_OK; - if (!(ns & NS_LAST)) continue; - } else { /* Could not find the object */ - if (!(ns & NS_LAST)) res = FR_NO_PATH; + if (res == FR_NO_FILE) { /* Object is not found */ + if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, */ + dp->sclust = 0; dp->dir = 0; /* it is the root directory and stay there */ + if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */ + res = FR_OK; /* Ended at the root directroy. Function completed. */ + } else { /* Could not find the object */ + if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */ + } } break; } - if (ns & NS_LAST) break; /* Last segment match. Function completed. */ - dir = dj->dir; /* There is next segment. Follow the sub directory */ - if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */ + if (ns & NS_LAST) break; /* Last segment matched. Function completed. */ + dir = dp->dir; /* Follow the sub-directory */ + if (!(dir[DIR_Attr] & AM_DIR)) { /* It is not a sub-directory and cannot follow */ res = FR_NO_PATH; break; } - dj->sclust = ld_clust(dj->fs, dir); + dp->sclust = ld_clust(dp->fs, dir); } } @@ -2034,23 +2071,25 @@ FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ /*-----------------------------------------------------------------------*/ -/* Load a sector and check if it is an FAT Volume Boot Record */ +/* Load a sector and check if it is an FAT boot sector */ /*-----------------------------------------------------------------------*/ static -BYTE check_fs ( /* 0:FAT-VBR, 1:Any BR but not FAT, 2:Not a BR, 3:Disk error */ - FATFS *fs, /* File system object */ +BYTE check_fs ( /* 0:FAT boor sector, 1:Valid boor sector but not FAT, 2:Not a boot sector, 3:Disk error */ + FATFS* fs, /* File system object */ DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */ ) { - if (disk_read(fs->drv, fs->win, sect, 1) != RES_OK) /* Load boot record */ + fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */ + if (move_window(fs, sect) != FR_OK) /* Load boot record */ return 3; - if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */ + + if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */ return 2; - if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */ + if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */ return 0; - if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146) + if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */ return 0; return 1; @@ -2060,50 +2099,39 @@ BYTE check_fs ( /* 0:FAT-VBR, 1:Any BR but not FAT, 2:Not a BR, 3:Disk error */ /*-----------------------------------------------------------------------*/ -/* Check if the file system object is valid or not */ +/* Find logical drive and check if the volume is mounted */ /*-----------------------------------------------------------------------*/ static -FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */ - const TCHAR **path, /* Pointer to pointer to the path name (drive number) */ - FATFS **rfs, /* Pointer to pointer to the found file system object */ +FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */ + FATFS** rfs, /* Pointer to pointer to the found file system object */ + const TCHAR** path, /* Pointer to pointer to the path name (drive number) */ BYTE wmode /* !=0: Check write protection for write access */ ) { - BYTE fmt, b, pi, *tbl; - UINT vol; + BYTE fmt; + int vol; DSTATUS stat; DWORD bsect, fasize, tsect, sysect, nclst, szbfat; WORD nrsv; - const TCHAR *p = *path; FATFS *fs; /* Get logical drive number from the path name */ - vol = p[0] - '0'; /* Is there a drive number? */ - if (vol <= 9 && p[1] == ':') { /* Found a drive number, get and strip it */ - p += 2; *path = p; /* Return pointer to the path name */ - } else { /* No drive number, use default drive */ -#if _FS_RPATH - vol = CurrVol; /* Use current drive */ -#else - vol = 0; /* Use drive 0 */ -#endif - } + *rfs = 0; + vol = get_ldnumber(path); + if (vol < 0) return FR_INVALID_DRIVE; /* Check if the file system object is valid or not */ - *rfs = 0; - if (vol >= _VOLUMES) /* Is the drive number valid? */ - return FR_INVALID_DRIVE; - fs = FatFs[vol]; /* Get corresponding file system object */ + fs = FatFs[vol]; /* Get pointer to the file system object */ if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */ - ENTER_FF(fs); /* Lock volume */ + ENTER_FF(fs); /* Lock the volume */ + *rfs = fs; /* Return pointer to the file system object */ - *rfs = fs; /* Return pointer to the corresponding file system object */ if (fs->fs_type) { /* If the volume has been mounted */ stat = disk_status(fs->drv); - if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized (has not been changed), */ + if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */ if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check write protection if needed */ return FR_WRITE_PROTECTED; return FR_OK; /* The file system object is valid */ @@ -2120,24 +2148,29 @@ FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */ return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */ if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check disk write protection if needed */ return FR_WRITE_PROTECTED; -#if _MAX_SS != 512 /* Get disk sector size (variable sector size cfg only) */ +#if _MAX_SS != 512 /* Get sector size (variable sector size cfg only) */ if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &fs->ssize) != RES_OK) return FR_DISK_ERR; #endif - /* Search FAT partition on the drive. Supports only generic partitions, FDISK and SFD. */ - fmt = check_fs(fs, bsect = 0); /* Load sector 0 and check if it is an FAT-VBR (in SFD) */ - if (LD2PT(vol) && !fmt) fmt = 1; /* Force non-SFD if the volume is forced partition */ - if (fmt == 1) { /* Not an FAT-VBR, the physical drive can be partitioned */ - /* Check the partition listed in the partition table */ - pi = LD2PT(vol); - if (pi) pi--; - tbl = &fs->win[MBR_Table + pi * SZ_PTE];/* Partition table */ - if (tbl[4]) { /* Is the partition existing? */ - bsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */ - fmt = check_fs(fs, bsect); /* Check the partition */ + /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */ + bsect = 0; + fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT boot sector as SFD */ + if (fmt == 1 || (!fmt && (LD2PT(vol)))) { /* Not an FAT boot sector or forced partition number */ + UINT i; + DWORD br[4]; + + for (i = 0; i < 4; i++) { /* Get partition offset */ + BYTE *pt = fs->win+MBR_Table + i * SZ_PTE; + br[i] = pt[4] ? LD_DWORD(&pt[8]) : 0; } + i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */ + if (i) i--; + do { /* Find an FAT volume */ + bsect = br[i]; + fmt = bsect ? check_fs(fs, bsect) : 2; /* Check the partition */ + } while (!LD2PT(vol) && fmt && ++i < 4); } - if (fmt == 3) return FR_DISK_ERR; + if (fmt == 3) return FR_DISK_ERR; /* An error occured in the disk I/O layer */ if (fmt) return FR_NO_FILESYSTEM; /* No FAT volume is found */ /* An FAT volume is found. Following code initializes the file system object */ @@ -2149,21 +2182,24 @@ FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */ if (!fasize) fasize = LD_DWORD(fs->win+BPB_FATSz32); fs->fsize = fasize; - fs->n_fats = b = fs->win[BPB_NumFATs]; /* Number of FAT copies */ - if (b != 1 && b != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */ - fasize *= b; /* Number of sectors for FAT area */ + fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */ + if (fs->n_fats != 1 && fs->n_fats != 2) /* (Must be 1 or 2) */ + return FR_NO_FILESYSTEM; + fasize *= fs->n_fats; /* Number of sectors for FAT area */ - fs->csize = b = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */ - if (!b || (b & (b - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */ + fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */ + if (!fs->csize || (fs->csize & (fs->csize - 1))) /* (Must be power of 2) */ + return FR_NO_FILESYSTEM; fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt); /* Number of root directory entries */ - if (fs->n_rootdir % (SS(fs) / SZ_DIR)) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be sector aligned) */ + if (fs->n_rootdir % (SS(fs) / SZ_DIR)) /* (Must be sector aligned) */ + return FR_NO_FILESYSTEM; tsect = LD_WORD(fs->win+BPB_TotSec16); /* Number of sectors on the volume */ if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32); nrsv = LD_WORD(fs->win+BPB_RsvdSecCnt); /* Number of reserved sectors */ - if (!nrsv) return FR_NO_FILESYSTEM; /* (BPB_RsvdSecCnt must not be 0) */ + if (!nrsv) return FR_NO_FILESYSTEM; /* (Must not be 0) */ /* Determine the FAT sub type */ sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIR); /* RSV+FAT+DIR */ @@ -2194,30 +2230,32 @@ FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */ #if !_FS_READONLY /* Initialize cluster allocation information */ - fs->free_clust = 0xFFFFFFFF; - fs->last_clust = 0; + fs->last_clust = fs->free_clust = 0xFFFFFFFF; /* Get fsinfo if available */ - if (fmt == FS_FAT32) { - fs->fsi_flag = 0; - fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo); - if (disk_read(fs->drv, fs->win, fs->fsi_sector, 1) == RES_OK && - LD_WORD(fs->win+BS_55AA) == 0xAA55 && - LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 && - LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) { - fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free); - fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count); + fs->fsi_flag = 0x80; + if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo is 1 */ + && LD_WORD(fs->win+BPB_FSInfo) == 1 + && move_window(fs, bsect + 1) == FR_OK) + { + fs->fsi_flag = 0; + if (LD_WORD(fs->win+BS_55AA) == 0xAA55 /* Load FSINFO data if available */ + && LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 + && LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) + { +#if !_FS_NOFSINFO + fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count); +#endif + fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free); } } #endif - fs->fs_type = fmt; /* FAT sub-type */ - fs->id = ++Fsid; /* File system mount ID */ - fs->winsect = 0; /* Invalidate sector cache */ - fs->wflag = 0; + fs->fs_type = fmt; /* FAT sub-type */ + fs->id = ++Fsid; /* File system mount ID */ #if _FS_RPATH - fs->cdir = 0; /* Current directory (root dir) */ + fs->cdir = 0; /* Current directory (root dir) */ #endif -#if _FS_LOCK /* Clear file lock semaphores */ +#if _FS_LOCK /* Clear file lock semaphores */ clear_lock(fs); #endif @@ -2228,7 +2266,7 @@ FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */ /*-----------------------------------------------------------------------*/ -/* Check if the file/dir object is valid or not */ +/* Check if the file/directory object is valid or not */ /*-----------------------------------------------------------------------*/ static @@ -2236,7 +2274,7 @@ FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */ void* obj /* Pointer to the object FIL/DIR to check validity */ ) { - FIL *fil = (FIL*)obj; /* Assuming offset of fs and id in the FIL/DIR is identical */ + FIL *fil = (FIL*)obj; /* Assuming offset of .fs and .id in the FIL/DIR structure is identical */ if (!fil || !fil->fs || !fil->fs->fs_type || fil->fs->id != fil->id) @@ -2266,36 +2304,42 @@ FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */ /*-----------------------------------------------------------------------*/ FRESULT f_mount ( - BYTE vol, /* Logical drive number to be mounted/unmounted */ - FATFS *fs /* Pointer to new file system object (NULL for unmount)*/ + FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/ + const TCHAR* path, /* Logical drive number to be mounted/unmounted */ + BYTE opt /* 0:Do not mount (delayed mount), 1:Mount immediately */ ) { - FATFS *rfs; + FATFS *cfs; + int vol; + FRESULT res; - if (vol >= _VOLUMES) /* Check if the drive number is valid */ - return FR_INVALID_DRIVE; - rfs = FatFs[vol]; /* Get current fs object */ + vol = get_ldnumber(&path); + if (vol < 0) return FR_INVALID_DRIVE; + cfs = FatFs[vol]; /* Pointer to fs object */ - if (rfs) { + if (cfs) { #if _FS_LOCK - clear_lock(rfs); + clear_lock(cfs); #endif -#if _FS_REENTRANT /* Discard sync object of the current volume */ - if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR; +#if _FS_REENTRANT /* Discard sync object of the current volume */ + if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR; #endif - rfs->fs_type = 0; /* Clear old fs object */ + cfs->fs_type = 0; /* Clear old fs object */ } if (fs) { - fs->fs_type = 0; /* Clear new fs object */ -#if _FS_REENTRANT /* Create sync object for the new volume */ + fs->fs_type = 0; /* Clear new fs object */ +#if _FS_REENTRANT /* Create sync object for the new volume */ if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR; #endif } - FatFs[vol] = fs; /* Register new fs object */ + FatFs[vol] = fs; /* Register new fs object */ - return FR_OK; + if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */ + + res = find_volume(&fs, &path, 0); /* Force mounted the volume */ + LEAVE_FF(fs, res); } @@ -2306,8 +2350,8 @@ FRESULT f_mount ( /*-----------------------------------------------------------------------*/ FRESULT f_open ( - FIL *fp, /* Pointer to the blank file object */ - const TCHAR *path, /* Pointer to the file name */ + FIL* fp, /* Pointer to the blank file object */ + const TCHAR* path, /* Pointer to the file name */ BYTE mode /* Access mode and file open mode flags */ ) { @@ -2320,12 +2364,13 @@ FRESULT f_open ( if (!fp) return FR_INVALID_OBJECT; fp->fs = 0; /* Clear file object */ + /* Get logical drive number */ #if !_FS_READONLY mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW; - res = chk_mounted(&path, &dj.fs, (BYTE)(mode & ~FA_READ)); + res = find_volume(&dj.fs, &path, (BYTE)(mode & ~FA_READ)); #else mode &= FA_READ; - res = chk_mounted(&path, &dj.fs, 0); + res = find_volume(&dj.fs, &path, 0); #endif if (res == FR_OK) { INIT_BUF(dj); @@ -2333,7 +2378,7 @@ FRESULT f_open ( dir = dj.dir; #if !_FS_READONLY /* R/W configuration */ if (res == FR_OK) { - if (!dir) /* Current dir itself */ + if (!dir) /* Default directory itself */ res = FR_INVALID_NAME; #if _FS_LOCK else @@ -2363,14 +2408,14 @@ FRESULT f_open ( } } if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */ - dw = get_fattime(); /* Created time */ + dw = get_fattime(); /* Created time */ ST_DWORD(dir+DIR_CrtTime, dw); - dir[DIR_Attr] = 0; /* Reset attribute */ - ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */ - cl = ld_clust(dj.fs, dir); /* Get start cluster */ - st_clust(dir, 0); /* cluster = 0 */ + dir[DIR_Attr] = 0; /* Reset attribute */ + ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */ + cl = ld_clust(dj.fs, dir); /* Get start cluster */ + st_clust(dir, 0); /* cluster = 0 */ dj.fs->wflag = 1; - if (cl) { /* Remove the cluster chain if exist */ + if (cl) { /* Remove the cluster chain if exist */ dw = dj.fs->winsect; res = remove_chain(dj.fs, cl); if (res == FR_OK) { @@ -2381,8 +2426,8 @@ FRESULT f_open ( } } else { /* Open an existing file */ - if (res == FR_OK) { /* Follow succeeded */ - if (dir[DIR_Attr] & AM_DIR) { /* It is a directory */ + if (res == FR_OK) { /* Follow succeeded */ + if (dir[DIR_Attr] & AM_DIR) { /* It is a directory */ res = FR_NO_FILE; } else { if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */ @@ -2391,9 +2436,9 @@ FRESULT f_open ( } } if (res == FR_OK) { - if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */ + if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */ mode |= FA__WRITTEN; - fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */ + fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */ fp->dir_ptr = dir; #if _FS_LOCK fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0); @@ -2404,7 +2449,7 @@ FRESULT f_open ( #else /* R/O configuration */ if (res == FR_OK) { /* Follow succeeded */ dir = dj.dir; - if (!dir) { /* Current dir itself */ + if (!dir) { /* Current directory itself */ res = FR_INVALID_NAME; } else { if (dir[DIR_Attr] & AM_DIR) /* It is a directory */ @@ -2416,6 +2461,7 @@ FRESULT f_open ( if (res == FR_OK) { fp->flag = mode; /* File access mode */ + fp->err = 0; /* Clear error flag */ fp->sclust = ld_clust(dj.fs, dir); /* File start cluster */ fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */ fp->fptr = 0; /* File pointer */ @@ -2423,7 +2469,8 @@ FRESULT f_open ( #if _USE_FASTSEEK fp->cltbl = 0; /* Normal seek mode */ #endif - fp->fs = dj.fs; fp->id = dj.fs->id; /* Validate file object */ + fp->fs = dj.fs; /* Validate file object */ + fp->id = fp->fs->id; } } @@ -2438,10 +2485,10 @@ FRESULT f_open ( /*-----------------------------------------------------------------------*/ FRESULT f_read ( - FIL *fp, /* Pointer to the file object */ - void *buff, /* Pointer to data buffer */ + FIL* fp, /* Pointer to the file object */ + void* buff, /* Pointer to data buffer */ UINT btr, /* Number of bytes to read */ - UINT *br /* Pointer to number of bytes read */ + UINT* br /* Pointer to number of bytes read */ ) { FRESULT res; @@ -2454,8 +2501,8 @@ FRESULT f_read ( res = validate(fp); /* Check validity */ if (res != FR_OK) LEAVE_FF(fp->fs, res); - if (fp->flag & FA__ERROR) /* Aborted file? */ - LEAVE_FF(fp->fs, FR_INT_ERR); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); if (!(fp->flag & FA_READ)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); remain = fp->fsize - fp->fptr; @@ -2487,7 +2534,7 @@ FRESULT f_read ( if (cc) { /* Read maximum contiguous sectors directly */ if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */ cc = fp->fs->csize - csect; - if (disk_read(fp->fs->drv, rbuff, sect, (BYTE)cc) != RES_OK) + if (disk_read(fp->fs->drv, rbuff, sect, cc)) ABORT(fp->fs, FR_DISK_ERR); #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */ #if _FS_TINY @@ -2505,12 +2552,12 @@ FRESULT f_read ( if (fp->dsect != sect) { /* Load data sector if not in cache */ #if !_FS_READONLY if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */ - if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1)) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif - if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK) /* Fill sector cache */ + if (disk_read(fp->fs->drv, fp->buf, sect, 1)) /* Fill sector cache */ ABORT(fp->fs, FR_DISK_ERR); } #endif @@ -2539,10 +2586,10 @@ FRESULT f_read ( /*-----------------------------------------------------------------------*/ FRESULT f_write ( - FIL *fp, /* Pointer to the file object */ + FIL* fp, /* Pointer to the file object */ const void *buff, /* Pointer to the data to be written */ UINT btw, /* Number of bytes to write */ - UINT *bw /* Pointer to number of bytes written */ + UINT* bw /* Pointer to number of bytes written */ ) { FRESULT res; @@ -2556,11 +2603,11 @@ FRESULT f_write ( res = validate(fp); /* Check validity */ if (res != FR_OK) LEAVE_FF(fp->fs, res); - if (fp->flag & FA__ERROR) /* Aborted file? */ - LEAVE_FF(fp->fs, FR_INT_ERR); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); if (!(fp->flag & FA_WRITE)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); - if ((DWORD)(fp->fsize + btw) < fp->fsize) btw = 0; /* File size cannot reach 4GB */ + if (fp->fptr + btw < fp->fptr) btw = 0; /* File size cannot reach 4GB */ for ( ; btw; /* Repeat until all data written */ wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) { @@ -2589,7 +2636,7 @@ FRESULT f_write ( ABORT(fp->fs, FR_DISK_ERR); #else if (fp->flag & FA__DIRTY) { /* Write-back sector cache */ - if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1)) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } @@ -2601,8 +2648,9 @@ FRESULT f_write ( if (cc) { /* Write maximum contiguous sectors directly */ if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */ cc = fp->fs->csize - csect; - if (disk_write(fp->fs->drv, wbuff, sect, (BYTE)cc) != RES_OK) + if (disk_write(fp->fs->drv, wbuff, sect, cc)) ABORT(fp->fs, FR_DISK_ERR); +#if _FS_MINIMIZE <= 2 #if _FS_TINY if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */ mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs)); @@ -2613,6 +2661,7 @@ FRESULT f_write ( mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs)); fp->flag &= ~FA__DIRTY; } +#endif #endif wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ continue; @@ -2625,7 +2674,7 @@ FRESULT f_write ( #else if (fp->dsect != sect) { /* Fill sector cache with file data */ if (fp->fptr < fp->fsize && - disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK) + disk_read(fp->fs->drv, fp->buf, sect, 1)) ABORT(fp->fs, FR_DISK_ERR); } #endif @@ -2654,11 +2703,11 @@ FRESULT f_write ( /*-----------------------------------------------------------------------*/ -/* Synchronize the File Object */ +/* Synchronize the File */ /*-----------------------------------------------------------------------*/ FRESULT f_sync ( - FIL *fp /* Pointer to the file object */ + FIL* fp /* Pointer to the file object */ ) { FRESULT res; @@ -2669,9 +2718,10 @@ FRESULT f_sync ( res = validate(fp); /* Check validity of the object */ if (res == FR_OK) { if (fp->flag & FA__WRITTEN) { /* Has the file been written? */ -#if !_FS_TINY /* Write-back dirty buffer */ + /* Write-back dirty buffer */ +#if !_FS_TINY if (fp->flag & FA__DIRTY) { - if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1)) LEAVE_FF(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } @@ -2716,28 +2766,28 @@ FRESULT f_close ( res = validate(fp); { #if _FS_REENTRANT - FATFS *fs = fp->fs; + FATFS *fs = 0; + if (res == FR_OK) fs = fp->fs; /* Get corresponding file system object */ #endif - if (res == FR_OK) fp->fs = 0; /* Discard file object */ + if (res == FR_OK) fp->fs = 0; /* Invalidate file object */ LEAVE_FF(fs, res); } #else - res = f_sync(fp); /* Flush cached data */ + res = f_sync(fp); /* Flush cached data */ #if _FS_LOCK - if (res == FR_OK) { /* Decrement open counter */ + if (res == FR_OK) { /* Decrement open counter */ #if _FS_REENTRANT - FATFS *fs = fp->fs;; res = validate(fp); if (res == FR_OK) { - res = dec_lock(fp->lockid); - unlock_fs(fs, FR_OK); + res = dec_lock(fp->lockid); + unlock_fs(fp->fs, FR_OK); } #else res = dec_lock(fp->lockid); #endif } #endif - if (res == FR_OK) fp->fs = 0; /* Discard file object */ + if (res == FR_OK) fp->fs = 0; /* Invalidate file object */ return res; #endif } @@ -2746,26 +2796,30 @@ FRESULT f_close ( /*-----------------------------------------------------------------------*/ -/* Current Drive/Directory Handlings */ +/* Change Current Directory or Current Drive, Get Current Directory */ /*-----------------------------------------------------------------------*/ #if _FS_RPATH >= 1 - +#if _VOLUMES >= 2 FRESULT f_chdrive ( - BYTE drv /* Drive number */ + const TCHAR* path /* Drive number */ ) { - if (drv >= _VOLUMES) return FR_INVALID_DRIVE; + int vol; - CurrVol = drv; + + vol = get_ldnumber(&path); + if (vol < 0) return FR_INVALID_DRIVE; + + CurrVol = (BYTE)vol; return FR_OK; } - +#endif FRESULT f_chdir ( - const TCHAR *path /* Pointer to the directory path */ + const TCHAR* path /* Pointer to the directory path */ ) { FRESULT res; @@ -2773,7 +2827,8 @@ FRESULT f_chdir ( DEF_NAMEBUF; - res = chk_mounted(&path, &dj.fs, 0); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 0); if (res == FR_OK) { INIT_BUF(dj); res = follow_path(&dj, path); /* Follow the path */ @@ -2797,7 +2852,7 @@ FRESULT f_chdir ( #if _FS_RPATH >= 2 FRESULT f_getcwd ( - TCHAR *buff, /* Pointer to the directory path */ + TCHAR* buff, /* Pointer to the directory path */ UINT len /* Size of path */ ) { @@ -2811,20 +2866,21 @@ FRESULT f_getcwd ( *buff = 0; - res = chk_mounted((const TCHAR**)&buff, &dj.fs, 0); /* Get current volume */ + /* Get logical drive number */ + res = find_volume(&dj.fs, (const TCHAR**)&buff, 0); /* Get current volume */ if (res == FR_OK) { INIT_BUF(dj); - i = len; /* Bottom of buffer (dir stack base) */ - dj.sclust = dj.fs->cdir; /* Start to follow upper dir from current dir */ - while ((ccl = dj.sclust) != 0) { /* Repeat while current dir is a sub-dir */ - res = dir_sdi(&dj, 1); /* Get parent dir */ + i = len; /* Bottom of buffer (directory stack base) */ + dj.sclust = dj.fs->cdir; /* Start to follow upper directory from current directory */ + while ((ccl = dj.sclust) != 0) { /* Repeat while current directory is a sub-directory */ + res = dir_sdi(&dj, 1); /* Get parent directory */ if (res != FR_OK) break; res = dir_read(&dj, 0); if (res != FR_OK) break; - dj.sclust = ld_clust(dj.fs, dj.dir); /* Goto parent dir */ + dj.sclust = ld_clust(dj.fs, dj.dir); /* Goto parent directory */ res = dir_sdi(&dj, 0); if (res != FR_OK) break; - do { /* Find the entry links to the child dir */ + do { /* Find the entry links to the child directory */ res = dir_read(&dj, 0); if (res != FR_OK) break; if (ccl == ld_clust(dj.fs, dj.dir)) break; /* Found the entry */ @@ -2836,9 +2892,11 @@ FRESULT f_getcwd ( fno.lfname = buff; fno.lfsize = i; #endif - get_fileinfo(&dj, &fno); /* Get the dir name and push it to the buffer */ + get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */ tp = fno.fname; - if (_USE_LFN && *buff) tp = buff; +#if _USE_LFN + if (*buff) tp = buff; +#endif for (n = 0; tp[n]; n++) ; if (i < n + 3) { res = FR_NOT_ENOUGH_CORE; break; @@ -2848,11 +2906,13 @@ FRESULT f_getcwd ( } tp = buff; if (res == FR_OK) { +#if _VOLUMES >= 2 *tp++ = '0' + CurrVol; /* Put drive number */ *tp++ = ':'; - if (i == len) { /* Root-dir */ +#endif + if (i == len) { /* Root-directory */ *tp++ = '/'; - } else { /* Sub-dir */ + } else { /* Sub-directroy */ do /* Add stacked path str */ *tp++ = buff[i++]; while (i < len); @@ -2875,7 +2935,7 @@ FRESULT f_getcwd ( /*-----------------------------------------------------------------------*/ FRESULT f_lseek ( - FIL *fp, /* Pointer to the file object */ + FIL* fp, /* Pointer to the file object */ DWORD ofs /* File pointer from top of file */ ) { @@ -2884,8 +2944,8 @@ FRESULT f_lseek ( res = validate(fp); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); - if (fp->flag & FA__ERROR) /* Check abort flag */ - LEAVE_FF(fp->fs, FR_INT_ERR); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); #if _USE_FASTSEEK if (fp->cltbl) { /* Fast seek */ @@ -2929,12 +2989,12 @@ FRESULT f_lseek ( #if !_FS_TINY #if !_FS_READONLY if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */ - if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1)) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif - if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK) /* Load current sector */ + if (disk_read(fp->fs->drv, fp->buf, dsc, 1)) /* Load current sector */ ABORT(fp->fs, FR_DISK_ERR); #endif fp->dsect = dsc; @@ -3004,12 +3064,12 @@ FRESULT f_lseek ( #if !_FS_TINY #if !_FS_READONLY if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */ - if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1)) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif - if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK) /* Fill sector cache */ + if (disk_read(fp->fs->drv, fp->buf, nsect, 1)) /* Fill sector cache */ ABORT(fp->fs, FR_DISK_ERR); #endif fp->dsect = nsect; @@ -3033,41 +3093,50 @@ FRESULT f_lseek ( /*-----------------------------------------------------------------------*/ FRESULT f_opendir ( - DIR *dj, /* Pointer to directory object to create */ - const TCHAR *path /* Pointer to the directory path */ + DIR* dp, /* Pointer to directory object to create */ + const TCHAR* path /* Pointer to the directory path */ ) { FRESULT res; - FATFS *fs; + FATFS* fs; DEF_NAMEBUF; - if (!dj) return FR_INVALID_OBJECT; + if (!dp) return FR_INVALID_OBJECT; - res = chk_mounted(&path, &dj->fs, 0); - fs = dj->fs; + /* Get logical drive number */ + res = find_volume(&fs, &path, 0); if (res == FR_OK) { - INIT_BUF(*dj); - res = follow_path(dj, path); /* Follow the path to the directory */ + dp->fs = fs; + INIT_BUF(*dp); + res = follow_path(dp, path); /* Follow the path to the directory */ FREE_BUF(); if (res == FR_OK) { /* Follow completed */ - if (dj->dir) { /* It is not the root dir */ - if (dj->dir[DIR_Attr] & AM_DIR) { /* The object is a directory */ - dj->sclust = ld_clust(fs, dj->dir); - } else { /* The object is not a directory */ + if (dp->dir) { /* It is not the origin directory itself */ + if (dp->dir[DIR_Attr] & AM_DIR) /* The object is a sub directory */ + dp->sclust = ld_clust(fs, dp->dir); + else /* The object is a file */ res = FR_NO_PATH; - } } if (res == FR_OK) { - dj->id = fs->id; - res = dir_sdi(dj, 0); /* Rewind dir */ + dp->id = fs->id; + res = dir_sdi(dp, 0); /* Rewind directory */ +#if _FS_LOCK + if (res == FR_OK) { + if (dp->sclust) { + dp->lockid = inc_lock(dp, 0); /* Lock the sub directory */ + if (!dp->lockid) + res = FR_TOO_MANY_OPEN_FILES; + } else { + dp->lockid = 0; /* Root directory need not to be locked */ + } + } +#endif } } if (res == FR_NO_FILE) res = FR_NO_PATH; - if (res != FR_OK) dj->fs = 0; /* Invalidate the dir object if function faild */ - } else { - dj->fs = 0; } + if (res != FR_OK) dp->fs = 0; /* Invalidate the directory object if function faild */ LEAVE_FF(fs, res); } @@ -3076,34 +3145,62 @@ FRESULT f_opendir ( /*-----------------------------------------------------------------------*/ -/* Read Directory Entry in Sequence */ +/* Close Directory */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_closedir ( + DIR *dp /* Pointer to the directory object to be closed */ +) +{ + FRESULT res; + + + res = validate(dp); +#if _FS_LOCK + if (res == FR_OK) { /* Decrement open counter */ + if (dp->lockid) + res = dec_lock(dp->lockid); +#if _FS_REENTRANT + unlock_fs(dp->fs, FR_OK); +#endif + } +#endif + if (res == FR_OK) dp->fs = 0; /* Invalidate directory object */ + return res; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Read Directory Entries in Sequence */ /*-----------------------------------------------------------------------*/ FRESULT f_readdir ( - DIR *dj, /* Pointer to the open directory object */ - FILINFO *fno /* Pointer to file information to return */ + DIR* dp, /* Pointer to the open directory object */ + FILINFO* fno /* Pointer to file information to return */ ) { FRESULT res; DEF_NAMEBUF; - res = validate(dj); /* Check validity of the object */ + res = validate(dp); /* Check validity of the object */ if (res == FR_OK) { if (!fno) { - res = dir_sdi(dj, 0); /* Rewind the directory object */ + res = dir_sdi(dp, 0); /* Rewind the directory object */ } else { - INIT_BUF(*dj); - res = dir_read(dj, 0); /* Read an item */ - if (res == FR_NO_FILE) { /* Reached end of dir */ - dj->sect = 0; + INIT_BUF(*dp); + res = dir_read(dp, 0); /* Read an item */ + if (res == FR_NO_FILE) { /* Reached end of directory */ + dp->sect = 0; res = FR_OK; } if (res == FR_OK) { /* A valid entry is found */ - get_fileinfo(dj, fno); /* Get the object information */ - res = dir_next(dj, 0); /* Increment index for next */ + get_fileinfo(dp, fno); /* Get the object information */ + res = dir_next(dp, 0); /* Increment index for next */ if (res == FR_NO_FILE) { - dj->sect = 0; + dp->sect = 0; res = FR_OK; } } @@ -3111,7 +3208,7 @@ FRESULT f_readdir ( } } - LEAVE_FF(dj->fs, res); + LEAVE_FF(dp->fs, res); } @@ -3122,8 +3219,8 @@ FRESULT f_readdir ( /*-----------------------------------------------------------------------*/ FRESULT f_stat ( - const TCHAR *path, /* Pointer to the file path */ - FILINFO *fno /* Pointer to file information to return */ + const TCHAR* path, /* Pointer to the file path */ + FILINFO* fno /* Pointer to file information to return */ ) { FRESULT res; @@ -3131,15 +3228,17 @@ FRESULT f_stat ( DEF_NAMEBUF; - res = chk_mounted(&path, &dj.fs, 0); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 0); if (res == FR_OK) { INIT_BUF(dj); res = follow_path(&dj, path); /* Follow the file path */ if (res == FR_OK) { /* Follow completed */ - if (dj.dir) /* Found an object */ - get_fileinfo(&dj, fno); - else /* It is root dir */ + if (dj.dir) { /* Found an object */ + if (fno) get_fileinfo(&dj, fno); + } else { /* It is root directory */ res = FR_INVALID_NAME; + } } FREE_BUF(); } @@ -3155,9 +3254,9 @@ FRESULT f_stat ( /*-----------------------------------------------------------------------*/ FRESULT f_getfree ( - const TCHAR *path, /* Path name of the logical drive number */ - DWORD *nclst, /* Pointer to a variable to return number of free clusters */ - FATFS **fatfs /* Pointer to return pointer to corresponding file system object */ + const TCHAR* path, /* Path name of the logical drive number */ + DWORD* nclst, /* Pointer to a variable to return number of free clusters */ + FATFS** fatfs /* Pointer to return pointer to corresponding file system object */ ) { FRESULT res; @@ -3167,8 +3266,8 @@ FRESULT f_getfree ( BYTE fat, *p; - /* Get drive number */ - res = chk_mounted(&path, fatfs, 0); + /* Get logical drive number */ + res = find_volume(fatfs, &path, 0); fs = *fatfs; if (res == FR_OK) { /* If free_clust is valid, return it without full cluster scan */ @@ -3207,7 +3306,7 @@ FRESULT f_getfree ( } while (--clst); } fs->free_clust = n; - if (fat == FS_FAT32) fs->fsi_flag = 1; + fs->fsi_flag |= 1; *nclst = n; } } @@ -3222,7 +3321,7 @@ FRESULT f_getfree ( /*-----------------------------------------------------------------------*/ FRESULT f_truncate ( - FIL *fp /* Pointer to the file object */ + FIL* fp /* Pointer to the file object */ ) { FRESULT res; @@ -3231,8 +3330,8 @@ FRESULT f_truncate ( res = validate(fp); /* Check validity of the object */ if (res == FR_OK) { - if (fp->flag & FA__ERROR) { /* Check abort flag */ - res = FR_INT_ERR; + if (fp->err) { /* Check error */ + res = (FRESULT)fp->err; } else { if (!(fp->flag & FA_WRITE)) /* Check access mode */ res = FR_DENIED; @@ -3255,8 +3354,16 @@ FRESULT f_truncate ( if (res == FR_OK) res = remove_chain(fp->fs, ncl); } } +#if !_FS_TINY + if (res == FR_OK && (fp->flag & FA__DIRTY)) { + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1)) + res = FR_DISK_ERR; + else + fp->flag &= ~FA__DIRTY; + } +#endif } - if (res != FR_OK) fp->flag |= FA__ERROR; + if (res != FR_OK) fp->err = (FRESULT)res; } LEAVE_FF(fp->fs, res); @@ -3270,7 +3377,7 @@ FRESULT f_truncate ( /*-----------------------------------------------------------------------*/ FRESULT f_unlink ( - const TCHAR *path /* Pointer to the file or directory path */ + const TCHAR* path /* Pointer to the file or directory path */ ) { FRESULT res; @@ -3280,7 +3387,8 @@ FRESULT f_unlink ( DEF_NAMEBUF; - res = chk_mounted(&path, &dj.fs, 1); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); if (res == FR_OK) { INIT_BUF(dj); res = follow_path(&dj, path); /* Follow the file path */ @@ -3302,14 +3410,14 @@ FRESULT f_unlink ( if (dclst < 2) { res = FR_INT_ERR; } else { - mem_cpy(&sdj, &dj, sizeof (DIR)); /* Check if the sub-dir is empty or not */ + mem_cpy(&sdj, &dj, sizeof (DIR)); /* Check if the sub-directory is empty or not */ sdj.sclust = dclst; res = dir_sdi(&sdj, 2); /* Exclude dot entries */ if (res == FR_OK) { res = dir_read(&sdj, 0); /* Read an item */ - if (res == FR_OK /* Not empty dir */ + if (res == FR_OK /* Not empty directory */ #if _FS_RPATH - || dclst == dj.fs->cdir /* Current dir */ + || dclst == dj.fs->cdir /* Current directory */ #endif ) res = FR_DENIED; if (res == FR_NO_FILE) res = FR_OK; /* Empty */ @@ -3339,7 +3447,7 @@ FRESULT f_unlink ( /*-----------------------------------------------------------------------*/ FRESULT f_mkdir ( - const TCHAR *path /* Pointer to the directory path */ + const TCHAR* path /* Pointer to the directory path */ ) { FRESULT res; @@ -3349,7 +3457,8 @@ FRESULT f_mkdir ( DEF_NAMEBUF; - res = chk_mounted(&path, &dj.fs, 1); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); if (res == FR_OK) { INIT_BUF(dj); res = follow_path(&dj, path); /* Follow the file path */ @@ -3374,7 +3483,7 @@ FRESULT f_mkdir ( ST_DWORD(dir+DIR_WrtTime, tm); st_clust(dir, dcl); mem_cpy(dir+SZ_DIR, dir, SZ_DIR); /* Create ".." entry */ - dir[33] = '.'; pcl = dj.sclust; + dir[SZ_DIR+1] = '.'; pcl = dj.sclust; if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase) pcl = 0; st_clust(dir+SZ_DIR, pcl); @@ -3412,7 +3521,7 @@ FRESULT f_mkdir ( /*-----------------------------------------------------------------------*/ FRESULT f_chmod ( - const TCHAR *path, /* Pointer to the file path */ + const TCHAR* path, /* Pointer to the file path */ BYTE value, /* Attribute bits */ BYTE mask /* Attribute mask to change */ ) @@ -3423,7 +3532,8 @@ FRESULT f_chmod ( DEF_NAMEBUF; - res = chk_mounted(&path, &dj.fs, 1); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); if (res == FR_OK) { INIT_BUF(dj); res = follow_path(&dj, path); /* Follow the file path */ @@ -3454,8 +3564,8 @@ FRESULT f_chmod ( /*-----------------------------------------------------------------------*/ FRESULT f_utime ( - const TCHAR *path, /* Pointer to the file/directory name */ - const FILINFO *fno /* Pointer to the time stamp to be set */ + const TCHAR* path, /* Pointer to the file/directory name */ + const FILINFO* fno /* Pointer to the time stamp to be set */ ) { FRESULT res; @@ -3464,7 +3574,8 @@ FRESULT f_utime ( DEF_NAMEBUF; - res = chk_mounted(&path, &dj.fs, 1); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); if (res == FR_OK) { INIT_BUF(dj); res = follow_path(&dj, path); /* Follow the file path */ @@ -3495,8 +3606,8 @@ FRESULT f_utime ( /*-----------------------------------------------------------------------*/ FRESULT f_rename ( - const TCHAR *path_old, /* Pointer to the old name */ - const TCHAR *path_new /* Pointer to the new name */ + const TCHAR* path_old, /* Pointer to the old name */ + const TCHAR* path_new /* Pointer to the new name */ ) { FRESULT res; @@ -3506,7 +3617,8 @@ FRESULT f_rename ( DEF_NAMEBUF; - res = chk_mounted(&path_old, &djo.fs, 1); + /* Get logical drive number of the source object */ + res = find_volume(&djo.fs, &path_old, 1); if (res == FR_OK) { djn.fs = djo.fs; INIT_BUF(djo); @@ -3585,12 +3697,12 @@ FRESULT f_getlabel ( UINT i, j; - /* Get logical drive */ - res = chk_mounted(&path, &dj.fs, 0); + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 0); /* Get volume label */ if (res == FR_OK && label) { - dj.sclust = 0; /* Open root dir */ + dj.sclust = 0; /* Open root directory */ res = dir_sdi(&dj, 0); if (res == FR_OK) { res = dir_read(&dj, 1); /* Get an entry with AM_VOL */ @@ -3601,8 +3713,8 @@ FRESULT f_getlabel ( do { w = (i < 11) ? dj.dir[i++] : ' '; if (IsDBCS1(w) && i < 11 && IsDBCS2(dj.dir[i])) - w = (w << 8) | dj.dir[i++]; - label[j++] = ff_convert(w, 1); + w = w << 8 | dj.dir[i++]; + label[j++] = ff_convert(w, 1); /* OEM -> Unicode */ } while (j < 11); #else mem_cpy(label, dj.dir, 11); @@ -3651,8 +3763,8 @@ FRESULT f_setlabel ( DWORD tm; - /* Get logical drive */ - res = chk_mounted(&label, &dj.fs, 1); + /* Get logical drive number */ + res = find_volume(&dj.fs, &label, 1); if (res) LEAVE_FF(dj.fs, res); /* Create a volume label in directory form */ @@ -3667,19 +3779,19 @@ FRESULT f_setlabel ( #else w = (BYTE)label[i++]; if (IsDBCS1(w)) - w = (j < 10 && i < sl && IsDBCS2(label[i])) ? (w << 8) | (BYTE)label[i++] : 0; + w = (j < 10 && i < sl && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0; #if _USE_LFN w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0); #else - if (IsLower(w)) w -= 0x20; /* To upper ASCII chars */ + if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */ #ifdef _EXCVT - if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended chars (SBCS cfg) */ + if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */ #else - if (!_DF1S && w >= 0x80) w = 0; /* Reject extended chars (ASCII cfg) */ + if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */ #endif #endif #endif - if (!w || chk_chr("\"*+,.:;<=>\?[]|\x7F", w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) /* Reject invalid chars for volume label */ + if (!w || chk_chr("\"*+,.:;<=>\?[]|\x7F", w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) /* Reject invalid characters for volume label */ LEAVE_FF(dj.fs, FR_INVALID_NAME); if (w >= 0x100) vn[j++] = (BYTE)(w >> 8); vn[j++] = (BYTE)w; @@ -3688,7 +3800,7 @@ FRESULT f_setlabel ( } /* Set volume label */ - dj.sclust = 0; /* Open root dir */ + dj.sclust = 0; /* Open root directory */ res = dir_sdi(&dj, 0); if (res == FR_OK) { res = dir_read(&dj, 1); /* Get an entry with AM_VOL */ @@ -3735,10 +3847,10 @@ FRESULT f_setlabel ( #if _USE_FORWARD && _FS_TINY FRESULT f_forward ( - FIL *fp, /* Pointer to the file object */ + FIL* fp, /* Pointer to the file object */ UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */ UINT btf, /* Number of bytes to forward */ - UINT *bf /* Pointer to number of bytes forwarded */ + UINT* bf /* Pointer to number of bytes forwarded */ ) { FRESULT res; @@ -3751,8 +3863,8 @@ FRESULT f_forward ( res = validate(fp); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); - if (fp->flag & FA__ERROR) /* Check error flag */ - LEAVE_FF(fp->fs, FR_INT_ERR); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); if (!(fp->flag & FA_READ)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); @@ -3793,18 +3905,19 @@ FRESULT f_forward ( /*-----------------------------------------------------------------------*/ /* Create File System on the Drive */ /*-----------------------------------------------------------------------*/ -#define N_ROOTDIR 512 /* Number of root dir entries for FAT12/16 */ +#define N_ROOTDIR 512 /* Number of root directory entries for FAT12/16 */ #define N_FATS 1 /* Number of FAT copies (1 or 2) */ FRESULT f_mkfs ( - BYTE vol, /* Logical drive number */ - BYTE sfd, /* Partitioning rule 0:FDISK, 1:SFD */ - UINT au /* Allocation unit size [bytes] */ + const TCHAR* path, /* Logical drive number */ + BYTE sfd, /* Partitioning rule 0:FDISK, 1:SFD */ + UINT au /* Allocation unit [bytes] */ ) { static const WORD vst[] = { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0}; static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512}; + int vol; BYTE fmt, md, sys, *tbl, pdrv, part; DWORD n_clst, vs, n, wsect; UINT i; @@ -3815,7 +3928,8 @@ FRESULT f_mkfs ( /* Check mounted drive and clear work area */ - if (vol >= _VOLUMES) return FR_INVALID_DRIVE; + vol = get_ldnumber(&path); + if (vol < 0) return FR_INVALID_DRIVE; if (sfd > 1) return FR_INVALID_PARAMETER; if (au & (au - 1)) return FR_INVALID_PARAMETER; fs = FatFs[vol]; @@ -3834,7 +3948,7 @@ FRESULT f_mkfs ( #endif if (_MULTI_PARTITION && part) { /* Get partition information from partition table in the MBR */ - if (disk_read(pdrv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR; + if (disk_read(pdrv, fs->win, 0, 1)) return FR_DISK_ERR; if (LD_WORD(fs->win+BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE]; if (!tbl[4]) return FR_MKFS_ABORTED; /* No partition? */ @@ -3896,17 +4010,23 @@ FRESULT f_mkfs ( || (fmt == FS_FAT32 && n_clst < MIN_FAT32)) return FR_MKFS_ABORTED; - switch (fmt) { /* Determine system ID for partition table */ - case FS_FAT12: sys = 0x01; break; - case FS_FAT16: sys = (n_vol < 0x10000) ? 0x04 : 0x06; break; - default: sys = 0x0C; + /* Determine system ID in the partition table */ + if (fmt == FS_FAT32) { + sys = 0x0C; /* FAT32X */ + } else { + if (fmt == FS_FAT12 && n_vol < 0x10000) { + sys = 0x01; /* FAT12(<65536) */ + } else { + sys = (n_vol < 0x10000) ? 0x04 : 0x06; /* FAT16(<65536) : FAT12/16(>=65536) */ + } } if (_MULTI_PARTITION && part) { /* Update system ID in the partition table */ tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE]; tbl[4] = sys; - if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR; + if (disk_write(pdrv, fs->win, 0, 1)) /* Write it to teh MBR */ + return FR_DISK_ERR; md = 0xF8; } else { if (sfd) { /* No partition table (SFD) */ @@ -3920,12 +4040,12 @@ FRESULT f_mkfs ( tbl[4] = sys; /* System type */ tbl[5] = 254; /* Partition end head */ n = (b_vol + n_vol) / 63 / 255; - tbl[6] = (BYTE)((n >> 2) | 63); /* Partition end sector */ + tbl[6] = (BYTE)(n >> 2 | 63); /* Partition end sector */ tbl[7] = (BYTE)n; /* End cylinder */ ST_DWORD(tbl+8, 63); /* Partition start in LBA */ ST_DWORD(tbl+12, n_vol); /* Partition size in LBA */ ST_WORD(fs->win+BS_55AA, 0xAA55); /* MBR signature */ - if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) /* Write it to the MBR sector */ + if (disk_write(pdrv, fs->win, 0, 1)) /* Write it to the MBR */ return FR_DISK_ERR; md = 0xF8; } @@ -3940,7 +4060,7 @@ FRESULT f_mkfs ( tbl[BPB_SecPerClus] = (BYTE)au; /* Sectors per cluster */ ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */ tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */ - i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR; /* Number of rootdir entries */ + i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR; /* Number of root directory entries */ ST_WORD(tbl+BPB_RootEntCnt, i); if (n_vol < 0x10000) { /* Number of total sectors */ ST_WORD(tbl+BPB_TotSec16, n_vol); @@ -3956,7 +4076,7 @@ FRESULT f_mkfs ( ST_DWORD(tbl+BS_VolID32, n); /* VSN */ ST_DWORD(tbl+BPB_FATSz32, n_fat); /* Number of sectors per FAT */ ST_DWORD(tbl+BPB_RootClus, 2); /* Root directory start cluster (2) */ - ST_WORD(tbl+BPB_FSInfo, 1); /* FSInfo record offset (VBR+1) */ + ST_WORD(tbl+BPB_FSInfo, 1); /* FSINFO record offset (VBR+1) */ ST_WORD(tbl+BPB_BkBootSec, 6); /* Backup boot record offset (VBR+6) */ tbl[BS_DrvNum32] = 0x80; /* Drive number */ tbl[BS_BootSig32] = 0x29; /* Extended boot signature */ @@ -3969,9 +4089,9 @@ FRESULT f_mkfs ( mem_cpy(tbl+BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */ } ST_WORD(tbl+BS_55AA, 0xAA55); /* Signature (Offset is fixed here regardless of sector size) */ - if (disk_write(pdrv, tbl, b_vol, 1) != RES_OK) /* Write it to the VBR sector */ + if (disk_write(pdrv, tbl, b_vol, 1)) /* Write it to the VBR sector */ return FR_DISK_ERR; - if (fmt == FS_FAT32) /* Write backup VBR if needed (VBR+6) */ + if (fmt == FS_FAT32) /* Write backup VBR if needed (VBR+6) */ disk_write(pdrv, tbl, b_vol + 6, 1); /* Initialize FAT area */ @@ -3986,13 +4106,13 @@ FRESULT f_mkfs ( n |= 0xFFFFFF00; ST_DWORD(tbl+0, n); /* Reserve cluster #0-1 (FAT32) */ ST_DWORD(tbl+4, 0xFFFFFFFF); - ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */ + ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root directory */ } - if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK) + if (disk_write(pdrv, tbl, wsect++, 1)) return FR_DISK_ERR; mem_set(tbl, 0, SS(fs)); /* Fill following FAT entries with zero */ for (n = 1; n < n_fat; n++) { /* This loop may take a time on FAT32 volume due to many single sector writes */ - if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK) + if (disk_write(pdrv, tbl, wsect++, 1)) return FR_DISK_ERR; } } @@ -4000,7 +4120,7 @@ FRESULT f_mkfs ( /* Initialize root directory */ i = (fmt == FS_FAT32) ? au : n_dir; do { - if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK) + if (disk_write(pdrv, tbl, wsect++, 1)) return FR_DISK_ERR; } while (--i); @@ -4013,7 +4133,7 @@ FRESULT f_mkfs ( } #endif - /* Create FSInfo if needed */ + /* Create FSINFO if needed */ if (fmt == FS_FAT32) { ST_DWORD(tbl+FSI_LeadSig, 0x41615252); ST_DWORD(tbl+FSI_StrucSig, 0x61417272); @@ -4028,6 +4148,7 @@ FRESULT f_mkfs ( } + #if _MULTI_PARTITION /*-----------------------------------------------------------------------*/ /* Divide Physical Drive */ @@ -4061,7 +4182,7 @@ FRESULT f_fdisk ( mem_set(buf, 0, _MAX_SS); p = buf + MBR_Table; b_cyl = 0; for (i = 0; i < 4; i++, p += SZ_PTE) { - p_cyl = (szt[i] <= 100) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl; + p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl; if (!p_cyl) continue; s_part = (DWORD)sz_cyl * b_cyl; sz_part = (DWORD)sz_cyl * p_cyl; @@ -4118,33 +4239,56 @@ TCHAR* f_gets ( UINT rc; - while (n < len - 1) { /* Read bytes until buffer gets filled */ + while (n < len - 1) { /* Read characters until buffer gets filled */ +#if _LFN_UNICODE +#if _STRF_ENCODE == 3 /* Read a character in UTF-8 */ f_read(fp, s, 1, &rc); - if (rc != 1) break; /* Break on EOF or error */ + if (rc != 1) break; c = s[0]; -#if _LFN_UNICODE /* Read a character in UTF-8 encoding */ if (c >= 0x80) { if (c < 0xC0) continue; /* Skip stray trailer */ if (c < 0xE0) { /* Two-byte sequence */ f_read(fp, s, 1, &rc); if (rc != 1) break; - c = ((c & 0x1F) << 6) | (s[0] & 0x3F); + c = (c & 0x1F) << 6 | (s[0] & 0x3F); if (c < 0x80) c = '?'; } else { if (c < 0xF0) { /* Three-byte sequence */ f_read(fp, s, 2, &rc); if (rc != 2) break; - c = (c << 12) | ((s[0] & 0x3F) << 6) | (s[1] & 0x3F); + c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); if (c < 0x800) c = '?'; } else { /* Reject four-byte sequence */ c = '?'; } } } +#elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */ + f_read(fp, s, 2, &rc); + if (rc != 2) break; + c = s[1] + (s[0] << 8); +#elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */ + f_read(fp, s, 2, &rc); + if (rc != 2) break; + c = s[0] + (s[1] << 8); +#else /* Read a character in ANSI/OEM */ + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = s[0]; + if (IsDBCS1(c)) { + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = (c << 8) + s[0]; + } + c = ff_convert(c, 1); /* OEM -> Unicode */ + if (!c) c = '?'; #endif -#if _USE_STRFUNC >= 2 - if (c == '\r') continue; /* Strip '\r' */ +#else /* Read a character without conversion */ + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = s[0]; #endif + if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */ *p++ = c; n++; if (c == '\n') break; /* Break on EOL */ @@ -4161,41 +4305,87 @@ TCHAR* f_gets ( /* Put a character to the file */ /*-----------------------------------------------------------------------*/ +typedef struct { + FIL* fp; + int idx, nchr; + BYTE buf[64]; +} putbuff; + + +static +void putc_bfd ( + putbuff* pb, + TCHAR c +) +{ + UINT bw; + int i; + + + if (_USE_STRFUNC == 2 && c == '\n') /* LF -> CRLF conversion */ + putc_bfd(pb, '\r'); + + i = pb->idx; /* Buffer write index (-1:error) */ + if (i < 0) return; + +#if _LFN_UNICODE +#if _STRF_ENCODE == 3 /* Write a character in UTF-8 */ + if (c < 0x80) { /* 7-bit */ + pb->buf[i++] = (BYTE)c; + } else { + if (c < 0x800) { /* 11-bit */ + pb->buf[i++] = (BYTE)(0xC0 | c >> 6); + } else { /* 16-bit */ + pb->buf[i++] = (BYTE)(0xE0 | c >> 12); + pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F)); + } + pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F)); + } +#elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */ + pb->buf[i++] = (BYTE)(c >> 8); + pb->buf[i++] = (BYTE)c; +#elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */ + pb->buf[i++] = (BYTE)c; + pb->buf[i++] = (BYTE)(c >> 8); +#else /* Write a character in ANSI/OEM */ + c = ff_convert(c, 0); /* Unicode -> OEM */ + if (!c) c = '?'; + if (c >= 0x100) + pb->buf[i++] = (BYTE)(c >> 8); + pb->buf[i++] = (BYTE)c; +#endif +#else /* Write a character without conversion */ + pb->buf[i++] = (BYTE)c; +#endif + + if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */ + f_write(pb->fp, pb->buf, (UINT)i, &bw); + i = (bw == (UINT)i) ? 0 : -1; + } + pb->idx = i; + pb->nchr++; +} + + + int f_putc ( TCHAR c, /* A character to be output */ FIL* fp /* Pointer to the file object */ ) { - UINT bw, btw; - BYTE s[3]; + putbuff pb; + UINT nw; -#if _USE_STRFUNC >= 2 - if (c == '\n') f_putc ('\r', fp); /* LF -> CRLF conversion */ -#endif + pb.fp = fp; /* Initialize output buffer */ + pb.nchr = pb.idx = 0; -#if _LFN_UNICODE /* Write the character in UTF-8 encoding */ - if (c < 0x80) { /* 7-bit */ - s[0] = (BYTE)c; - btw = 1; - } else { - if (c < 0x800) { /* 11-bit */ - s[0] = (BYTE)(0xC0 | (c >> 6)); - s[1] = (BYTE)(0x80 | (c & 0x3F)); - btw = 2; - } else { /* 16-bit */ - s[0] = (BYTE)(0xE0 | (c >> 12)); - s[1] = (BYTE)(0x80 | ((c >> 6) & 0x3F)); - s[2] = (BYTE)(0x80 | (c & 0x3F)); - btw = 3; - } - } -#else /* Write the character without conversion */ - s[0] = (BYTE)c; - btw = 1; -#endif - f_write(fp, s, btw, &bw); /* Write the char to the file */ - return (bw == btw) ? 1 : EOF; /* Return the result */ + putc_bfd(&pb, c); /* Put a character */ + + if ( pb.idx >= 0 /* Flush buffered characters to the file */ + && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK + && (UINT)pb.idx == nw) return pb.nchr; + return EOF; } @@ -4210,13 +4400,20 @@ int f_puts ( FIL* fp /* Pointer to the file object */ ) { - int n; + putbuff pb; + UINT nw; - for (n = 0; *str; str++, n++) { - if (f_putc(*str, fp) == EOF) return EOF; - } - return n; + pb.fp = fp; /* Initialize output buffer */ + pb.nchr = pb.idx = 0; + + while (*str) /* Put the string */ + putc_bfd(&pb, *str++); + + if ( pb.idx >= 0 /* Flush buffered characters to the file */ + && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK + && (UINT)pb.idx == nw) return pb.nchr; + return EOF; } @@ -4228,43 +4425,45 @@ int f_puts ( int f_printf ( FIL* fp, /* Pointer to the file object */ - const TCHAR* str, /* Pointer to the format string */ + const TCHAR* fmt, /* Pointer to the format string */ ... /* Optional arguments... */ ) { va_list arp; BYTE f, r; - UINT i, j, w; - ULONG v; + UINT nw, i, j, w; + DWORD v; TCHAR c, d, s[16], *p; - int res, chc, cc; + putbuff pb; - va_start(arp, str); + pb.fp = fp; /* Initialize output buffer */ + pb.nchr = pb.idx = 0; - for (cc = res = 0; cc != EOF; res += cc) { - c = *str++; + va_start(arp, fmt); + + for (;;) { + c = *fmt++; if (c == 0) break; /* End of string */ if (c != '%') { /* Non escape character */ - cc = f_putc(c, fp); - if (cc != EOF) cc = 1; + putc_bfd(&pb, c); continue; } w = f = 0; - c = *str++; + c = *fmt++; if (c == '0') { /* Flag: '0' padding */ - f = 1; c = *str++; + f = 1; c = *fmt++; } else { if (c == '-') { /* Flag: left justified */ - f = 2; c = *str++; + f = 2; c = *fmt++; } } while (IsDigit(c)) { /* Precision */ w = w * 10 + c - '0'; - c = *str++; + c = *fmt++; } if (c == 'l' || c == 'L') { /* Prefix: Size is long int */ - f |= 4; c = *str++; + f |= 4; c = *fmt++; } if (!c) break; d = c; @@ -4273,16 +4472,14 @@ int f_printf ( case 'S' : /* String */ p = va_arg(arp, TCHAR*); for (j = 0; p[j]; j++) ; - chc = 0; if (!(f & 2)) { - while (j++ < w) chc += (cc = f_putc(' ', fp)); + while (j++ < w) putc_bfd(&pb, ' '); } - chc += (cc = f_puts(p, fp)); - while (j++ < w) chc += (cc = f_putc(' ', fp)); - if (cc != EOF) cc = chc; + while (*p) putc_bfd(&pb, *p++); + while (j++ < w) putc_bfd(&pb, ' '); continue; case 'C' : /* Character */ - cc = f_putc((TCHAR)va_arg(arp, int), fp); continue; + putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue; case 'B' : /* Binary */ r = 2; break; case 'O' : /* Octal */ @@ -4293,11 +4490,11 @@ int f_printf ( case 'X' : /* Hexdecimal */ r = 16; break; default: /* Unknown type (pass-through) */ - cc = f_putc(c, fp); continue; + putc_bfd(&pb, c); continue; } /* Get an argument and put it in numeral */ - v = (f & 4) ? (ULONG)va_arg(arp, long) : ((d == 'D') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int)); + v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int)); if (d == 'D' && (v & 0x80000000)) { v = 0 - v; f |= 8; @@ -4310,15 +4507,17 @@ int f_printf ( } while (v && i < sizeof s / sizeof s[0]); if (f & 8) s[i++] = '-'; j = i; d = (f & 1) ? '0' : ' '; - chc = 0; - while (!(f & 2) && j++ < w) chc += (cc = f_putc(d, fp)); - do chc += (cc = f_putc(s[--i], fp)); while(i); - while (j++ < w) chc += (cc = f_putc(' ', fp)); - if (cc != EOF) cc = chc; + while (!(f & 2) && j++ < w) putc_bfd(&pb, d); + do putc_bfd(&pb, s[--i]); while (i); + while (j++ < w) putc_bfd(&pb, d); } va_end(arp); - return (cc == EOF) ? cc : res; + + if ( pb.idx >= 0 /* Flush buffered characters to the file */ + && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK + && (UINT)pb.idx == nw) return pb.nchr; + return EOF; } #endif /* !_FS_READONLY */ diff --git a/src/ff.h b/src/ff.h index eb60ebf..70cb299 100644 --- a/src/ff.h +++ b/src/ff.h @@ -1,5 +1,5 @@ /*---------------------------------------------------------------------------/ -/ FatFs - FAT file system module include file R0.09b (C)ChaN, 2013 +/ FatFs - FAT file system module include file R0.10 (C)ChaN, 2013 /----------------------------------------------------------------------------/ / FatFs module is a generic FAT file system module for small embedded systems. / This is a free software that opened for education, research and commercial @@ -15,7 +15,7 @@ /----------------------------------------------------------------------------*/ #ifndef _FATFS -#define _FATFS 82786 /* Revision ID */ +#define _FATFS 80960 /* Revision ID */ #ifdef __cplusplus extern "C" { @@ -43,7 +43,7 @@ extern PARTITION VolToPart[]; /* Volume - Partition resolution table */ #else /* Single partition configuration */ #define LD2PD(vol) (BYTE)(vol) /* Each logical drive is bound to the same physical drive number */ -#define LD2PT(vol) 0 /* Always mounts the 1st partition or in SFD */ +#define LD2PT(vol) 0 /* Find first valid partition or in SFD */ #endif @@ -78,9 +78,9 @@ typedef struct { BYTE fs_type; /* FAT sub-type (0:Not mounted) */ BYTE drv; /* Physical drive number */ BYTE csize; /* Sectors per cluster (1,2,4...128) */ - BYTE n_fats; /* Number of FAT copies (1,2) */ - BYTE wflag; /* win[] dirty flag (1:must be written back) */ - BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */ + BYTE n_fats; /* Number of FAT copies (1 or 2) */ + BYTE wflag; /* win[] flag (b0:dirty) */ + BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ WORD id; /* File system mount ID */ WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ #if _MAX_SS != 512 @@ -92,7 +92,6 @@ typedef struct { #if !_FS_READONLY DWORD last_clust; /* Last allocated cluster */ DWORD free_clust; /* Number of free clusters */ - DWORD fsi_sector; /* fsinfo sector (FAT32) */ #endif #if _FS_RPATH DWORD cdir; /* Current directory start cluster (0:root) */ @@ -104,7 +103,7 @@ typedef struct { DWORD dirbase; /* Root directory start sector (FAT32:Cluster#) */ DWORD database; /* Data start sector */ DWORD winsect; /* Current sector appearing in the win[] */ - BYTE win[_MAX_SS]; /* Disk access window for Directory, FAT (and Data on tiny cfg) */ + BYTE win[_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */ } FATFS; @@ -115,8 +114,8 @@ typedef struct { FATFS* fs; /* Pointer to the related file system object (**do not change order**) */ WORD id; /* Owner file system mount ID (**do not change order**) */ BYTE flag; /* File status flags */ - BYTE pad1; - DWORD fptr; /* File read/write pointer (0ed on file open) */ + BYTE err; /* Abort flag (error code) */ + DWORD fptr; /* File read/write pointer (Zeroed on file open) */ DWORD fsize; /* File size */ DWORD sclust; /* File data start cluster (0:no data cluster, always 0 when fsize is 0) */ DWORD clust; /* Current cluster of fpter */ @@ -126,7 +125,7 @@ typedef struct { BYTE* dir_ptr; /* Pointer to the directory entry in the window */ #endif #if _USE_FASTSEEK - DWORD* cltbl; /* Pointer to the cluster link map table (null on file open) */ + DWORD* cltbl; /* Pointer to the cluster link map table (Nulled on file open) */ #endif #if _FS_LOCK UINT lockid; /* File lock ID (index of file semaphore table Files[]) */ @@ -149,6 +148,9 @@ typedef struct { DWORD sect; /* Current sector */ BYTE* dir; /* Pointer to the current SFN entry in the win[] */ BYTE* fn; /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */ +#if _FS_LOCK + UINT lockid; /* File lock ID (index of file semaphore table Files[]) */ +#endif #if _USE_LFN WCHAR* lfn; /* Pointer to the LFN working buffer */ WORD lfn_idx; /* Last matched LFN index number (0xFFFF:No LFN) */ @@ -203,38 +205,39 @@ typedef enum { /*--------------------------------------------------------------*/ /* FatFs module application interface */ -FRESULT f_mount (BYTE vol, FATFS* fs); /* Mount/Unmount a logical drive */ FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */ -FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from a file */ -FRESULT f_lseek (FIL* fp, DWORD ofs); /* Move file pointer of a file object */ FRESULT f_close (FIL* fp); /* Close an open file object */ -FRESULT f_opendir (DIR* dj, const TCHAR* path); /* Open an existing directory */ -FRESULT f_readdir (DIR* dj, FILINFO* fno); /* Read a directory item */ -FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */ +FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from a file */ FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to a file */ -FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */ +FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */ +FRESULT f_lseek (FIL* fp, DWORD ofs); /* Move file pointer of a file object */ FRESULT f_truncate (FIL* fp); /* Truncate file */ FRESULT f_sync (FIL* fp); /* Flush cached data of a writing file */ +FRESULT f_opendir (DIR* dp, const TCHAR* path); /* Open a directory */ +FRESULT f_closedir (DIR* dp); /* Close an open directory */ +FRESULT f_readdir (DIR* dp, FILINFO* fno); /* Read a directory item */ +FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */ FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */ -FRESULT f_mkdir (const TCHAR* path); /* Create a new directory */ +FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */ +FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */ FRESULT f_chmod (const TCHAR* path, BYTE value, BYTE mask); /* Change attribute of the file/dir */ FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change times-tamp of the file/dir */ -FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */ -FRESULT f_chdrive (BYTE drv); /* Change current drive */ FRESULT f_chdir (const TCHAR* path); /* Change current directory */ +FRESULT f_chdrive (const TCHAR* path); /* Change current drive */ FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */ -FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* sn); /* Get volume label */ -FRESULT f_setlabel (const TCHAR* label); /* Set volume label */ -FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */ -FRESULT f_mkfs (BYTE vol, BYTE sfd, UINT au); /* Create a file system on the drive */ -FRESULT f_fdisk (BYTE pdrv, const DWORD szt[], void* work); /* Divide a physical drive into some partitions */ +FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */ +FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* sn); /* Get volume label */ +FRESULT f_setlabel (const TCHAR* label); /* Set volume label */ +FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */ +FRESULT f_mkfs (const TCHAR* path, BYTE sfd, UINT au); /* Create a file system on the volume */ +FRESULT f_fdisk (BYTE pdrv, const DWORD szt[], void* work); /* Divide a physical drive into some partitions */ int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */ int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */ int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */ TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */ #define f_eof(fp) (((fp)->fptr == (fp)->fsize) ? 1 : 0) -#define f_error(fp) (((fp)->flag & FA__ERROR) ? 1 : 0) +#define f_error(fp) ((fp)->err) #define f_tell(fp) ((fp)->fptr) #define f_size(fp) ((fp)->fsize) @@ -282,7 +285,6 @@ int ff_del_syncobj (_SYNC_t sobj); /* Delete a sync object */ #define FA_READ 0x01 #define FA_OPEN_EXISTING 0x00 -#define FA__ERROR 0x80 #if !_FS_READONLY #define FA_WRITE 0x02 diff --git a/src/ffconf.h b/src/ffconf.h index c5c5872..975e992 100644 --- a/src/ffconf.h +++ b/src/ffconf.h @@ -1,5 +1,5 @@ /*---------------------------------------------------------------------------/ -/ FatFs - FAT file system module configuration file R0.09b (C)ChaN, 2013 +/ FatFs - FAT file system module configuration file R0.10 (C)ChaN, 2013 /----------------------------------------------------------------------------/ / / CAUTION! Do not forget to make clean the project after any changes to @@ -7,7 +7,7 @@ / /----------------------------------------------------------------------------*/ #ifndef _FFCONF -#define _FFCONF 82786 /* Revision ID */ +#define _FFCONF 80960 /* Revision ID */ /*---------------------------------------------------------------------------/ @@ -22,18 +22,18 @@ #define _FS_READONLY 0 /* 0:Read/Write or 1:Read only */ /* Setting _FS_READONLY to 1 defines read only configuration. This removes -/ writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename, -/ f_truncate and useless f_getfree. */ +/ writing functions, f_write(), f_sync(), f_unlink(), f_mkdir(), f_chmod(), +/ f_rename(), f_truncate() and useless f_getfree(). */ #define _FS_MINIMIZE 0 /* 0 to 3 */ -/* The _FS_MINIMIZE option defines minimization level to remove some functions. +/* The _FS_MINIMIZE option defines minimization level to remove API functions. / -/ 0: Full function. -/ 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename -/ are removed. -/ 2: f_opendir and f_readdir are removed in addition to 1. -/ 3: f_lseek is removed in addition to 2. */ +/ 0: All basic functions are enabled. +/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_chmod(), f_utime(), +/ f_truncate() and f_rename() function are removed. +/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1. +/ 3: f_lseek() function is removed in addition to 2. */ #define _USE_STRFUNC 0 /* 0:Disable or 1-2:Enable */ @@ -41,7 +41,7 @@ #define _USE_MKFS 0 /* 0:Disable or 1:Enable */ -/* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */ +/* To enable f_mkfs() function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */ #define _USE_FASTSEEK 0 /* 0:Disable or 1:Enable */ @@ -53,7 +53,7 @@ #define _USE_FORWARD 0 /* 0:Disable or 1:Enable */ -/* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */ +/* To enable f_forward() function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */ /*---------------------------------------------------------------------------/ @@ -89,65 +89,84 @@ / 857 - Turkish (OEM) / 862 - Hebrew (OEM) / 874 - Thai (OEM, Windows) -/ 1 - ASCII only (Valid for non LFN cfg.) +/ 1 - ASCII (Valid for only non-LFN cfg.) */ #define _USE_LFN 0 /* 0 to 3 */ #define _MAX_LFN 255 /* Maximum LFN length to handle (12 to 255) */ -/* The _USE_LFN option switches the LFN support. +/* The _USE_LFN option switches the LFN feature. / -/ 0: Disable LFN feature. _MAX_LFN and _LFN_UNICODE have no effect. +/ 0: Disable LFN feature. _MAX_LFN has no effect. / 1: Enable LFN with static working buffer on the BSS. Always NOT reentrant. / 2: Enable LFN with dynamic working buffer on the STACK. / 3: Enable LFN with dynamic working buffer on the HEAP. / -/ The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. To enable LFN, -/ Unicode handling functions ff_convert() and ff_wtoupper() must be added -/ to the project. When enable to use heap, memory control functions -/ ff_memalloc() and ff_memfree() must be added to the project. */ +/ To enable LFN feature, Unicode handling functions ff_convert() and ff_wtoupper() +/ function must be added to the project. +/ The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. When use stack for the +/ working buffer, take care on stack overflow. When use heap memory for the working +/ buffer, memory management functions, ff_memalloc() and ff_memfree(), must be added +/ to the project. */ #define _LFN_UNICODE 0 /* 0:ANSI/OEM or 1:Unicode */ -/* To switch the character code set on FatFs API to Unicode, -/ enable LFN feature and set _LFN_UNICODE to 1. */ +/* To switch the character encoding on the FatFs API to Unicode, enable LFN feature +/ and set _LFN_UNICODE to 1. */ + + +#define _STRF_ENCODE 3 /* 0:ANSI/OEM, 1:UTF-16LE, 2:UTF-16BE, 3:UTF-8 */ +/* When Unicode API is enabled, character encoding on the all FatFs API is switched +/ to Unicode. This option selects the character encoding on the file to be read/written +/ via string functions, f_gets(), f_putc(), f_puts and f_printf(). +/ This option has no effect when _LFN_UNICODE is 0. */ #define _FS_RPATH 0 /* 0 to 2 */ /* The _FS_RPATH option configures relative path feature. / / 0: Disable relative path feature and remove related functions. -/ 1: Enable relative path. f_chdrive() and f_chdir() are available. -/ 2: f_getcwd() is available in addition to 1. +/ 1: Enable relative path. f_chdrive() and f_chdir() function are available. +/ 2: f_getcwd() function is available in addition to 1. / -/ Note that output of the f_readdir fnction is affected by this option. */ +/ Note that output of the f_readdir() fnction is affected by this option. */ /*---------------------------------------------------------------------------/ -/ Physical Drive Configurations +/ Drive/Volume Configurations /----------------------------------------------------------------------------*/ #define _VOLUMES 1 /* Number of volumes (logical drives) to be used. */ -#define _MAX_SS 512 /* 512, 1024, 2048 or 4096 */ -/* Maximum sector size to be handled. -/ Always set 512 for memory card and hard disk but a larger value may be -/ required for on-board flash memory, floppy disk and optical disk. -/ When _MAX_SS is larger than 512, it configures FatFs to variable sector size -/ and GET_SECTOR_SIZE command must be implememted to the disk_ioctl function. */ - - #define _MULTI_PARTITION 0 /* 0:Single partition, 1:Enable multiple partition */ /* When set to 0, each volume is bound to the same physical drive number and / it can mount only first primaly partition. When it is set to 1, each volume / is tied to the partitions listed in VolToPart[]. */ +#define _MAX_SS 512 /* 512, 1024, 2048 or 4096 */ +/* Maximum sector size to be handled. +/ Always set 512 for memory card and hard disk but a larger value may be +/ required for on-board flash memory, floppy disk and optical disk. +/ When _MAX_SS is larger than 512, it configures FatFs to variable sector size +/ and GET_SECTOR_SIZE command must be implemented to the disk_ioctl() function. */ + + #define _USE_ERASE 0 /* 0:Disable or 1:Enable */ -/* To enable sector erase feature, set _USE_ERASE to 1. CTRL_ERASE_SECTOR command -/ should be added to the disk_ioctl functio. */ +/* To enable sector erase feature, set _USE_ERASE to 1. Also CTRL_ERASE_SECTOR command +/ should be added to the disk_ioctl() function. */ + + +#define _FS_NOFSINFO 0 /* 0 or 1 */ +/* If you need to know the correct free space on the FAT32 volume, set this +/ option to 1 and f_getfree() function at first time after volume mount will +/ force a full FAT scan. +/ +/ 0: Load all informations in the FSINFO if available. +/ 1: Do not trust free cluster count in the FSINFO. +*/ @@ -156,16 +175,17 @@ /----------------------------------------------------------------------------*/ #define _WORD_ACCESS 0 /* 0 or 1 */ -/* Set 0 first and it is always compatible with all platforms. The _WORD_ACCESS -/ option defines which access method is used to the word data on the FAT volume. +/* The _WORD_ACCESS option is an only platform dependent option. It defines +/ which access method is used to the word data on the FAT volume. / -/ 0: Byte-by-byte access. -/ 1: Word access. Do not choose this unless following condition is met. +/ 0: Byte-by-byte access. Always compatible with all platforms. +/ 1: Word access. Do not choose this unless under both the following conditions. / -/ When the byte order on the memory is big-endian or address miss-aligned word -/ access results incorrect behavior, the _WORD_ACCESS must be set to 0. -/ If it is not the case, the value can also be set to 1 to improve the -/ performance and code size. +/ * Byte order on the memory is little-endian. +/ * Address miss-aligned word access is always allowed for all instructions. +/ +/ If it is the case, _WORD_ACCESS can also be set to 1 to improve performance +/ and reduce code size. */ @@ -176,11 +196,11 @@ #define _FS_TIMEOUT 1000 /* Timeout period in unit of time ticks */ #define _SYNC_t HANDLE /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */ -/* The _FS_REENTRANT option switches the reentrancy (thread safe) of the FatFs module. +/* The _FS_REENTRANT option switches the re-entrancy (thread safe) of the FatFs module. / -/ 0: Disable reentrancy. _SYNC_t and _FS_TIMEOUT have no effect. -/ 1: Enable reentrancy. Also user provided synchronization handlers, -/ ff_req_grant, ff_rel_grant, ff_del_syncobj and ff_cre_syncobj +/ 0: Disable re-entrancy. _SYNC_t and _FS_TIMEOUT have no effect. +/ 1: Enable re-entrancy. Also user provided synchronization handlers, +/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj() / function must be added to the project. */ diff --git a/src/integer.h b/src/integer.h index 16ad408..f254b2a 100644 --- a/src/integer.h +++ b/src/integer.h @@ -2,8 +2,8 @@ /* Integer type definitions for FatFs module */ /*-------------------------------------------*/ -#ifndef _INTEGER -#define _INTEGER +#ifndef _FF_INTEGER +#define _FF_INTEGER #ifdef _WIN32 /* FatFs development platform */ @@ -12,24 +12,20 @@ #else /* Embedded platform */ -/* These types must be 16-bit, 32-bit or larger integer */ -typedef int INT; -typedef unsigned int UINT; - -/* These types must be 8-bit integer */ -typedef char CHAR; -typedef unsigned char UCHAR; +/* This type MUST be 8 bit */ typedef unsigned char BYTE; -/* These types must be 16-bit integer */ +/* These types MUST be 16 bit */ typedef short SHORT; -typedef unsigned short USHORT; typedef unsigned short WORD; typedef unsigned short WCHAR; -/* These types must be 32-bit integer */ +/* These types MUST be 16 bit or 32 bit */ +typedef int INT; +typedef unsigned int UINT; + +/* These types MUST be 32 bit */ typedef long LONG; -typedef unsigned long ULONG; typedef unsigned long DWORD; #endif