1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Zynq > SD書込み (FatFS) > A. ファイル追記処理

Last updated at Posted at 2015-12-23

自分のメモ(2015/4/9)より

MicroZedで動作確認した。

ファイルへの追記処理

  1. #include "ff.h"を追加 (FatFS利用のため)
  2. FIL fil; /* file object */
  3. FATFS fatfs;
  4. f_mount(0, &fatfs); にてFAT形式をマウントする
  5. f_open(&fil, filename, FA_OPEN_ALWAYS | FA_WRITE);
  • FA_OPEN_ALWAYS >「既存のファイルを開きます。ファイルが無いときはファイルを作成します。追記の場合は、この方法でオープンした後、f_lseek関数でファイルの最後尾に移動してください。」
  1. f_lseek(&fil, f_size(&fil)); // ファイル終端へ移動
  2. f_write(&fil, szbuf, strlen(szbuf), &numWritten); // 書込み. numWrittenに書込み文字数が戻る
  • f_write()以外にf_printf()も使える
  1. f_close(&fil); または継続して書込みするなら f_sync()を使う
  2. f_mount(0, 0); // アンマウント

以下のコードをベアメタルアプリに追加してfileAppendTest()を実行すると0407.txtへファイル追加が行われる。

fileAppendTest.c
# include <string.h> // for strlen
# include "ff.h" // for FatFS
# define RET_NG (-1)
# define RET_OK (0)
static signed int fileAppendTest(void)
{
    FRESULT rc;
    FIL fil;
    FATFS fatfs;
    char szbuf[] = "hello World\r\n";
    UINT numWritten;
    //---
    int dbg; // for debug
 
    rc = f_mount(0, &fatfs);
    if (rc != FR_OK) {
        return RET_NG;
    }
 
    // create file if not found
    rc = f_open(&fil, "0407.txt", FA_OPEN_ALWAYS | FA_WRITE);
    if (rc != FR_OK) {
        return RET_NG;
    }
 
    // move to the last
    rc = f_lseek(&fil, f_size(&fil));
 
    rc = f_write(&fil, szbuf, strlen(szbuf), &numWritten);
    if (numWritten == 0) {
        dbg=1;
    }
 
  
    f_close(&fil);
 
    // unmount
    f_mount(0, 0);
    return RET_OK;
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?