Example of reading and writing text file in microSD card for DISCO-F746. DISCO-F746 で microSD カードのテキスト・ファイルの読み書きを行う例.

Dependencies:   BSP_DISCO_F746NG SDFileSystem_Warning_Fixed

main.cpp

Committer:
MikamiUitOpen
Date:
2016-11-14
Revision:
2:0705bf3a3e1e
Parent:
1:7aa80a497ed2

File content as of revision 2:0705bf3a3e1e:

//--------------------------------------------------------------
//  SD カードのテキスト・ファイルの読み書きの例
//
//  mount(), unmount() を使うことを除けば通常のテキストファイルの
//  読み書きと同じ.
//
//  2016/11/14, Copyright (c) 2016 MIKAMI, Naoki
//--------------------------------------------------------------

#include "mbed.h"
#include "SDFileSystem.h"   // SDFileSystem クラスを使うため

DigitalOut led_green(LED1);
SDFileSystem sd("sd");      // SDFileSystem: SD 用のクラス, 引数の文字列は任意

int main()
{
    printf("\r\nSD Text file write/read test: started\r\n\n");

    sd.mount(); // SD 用

    // SD へ書き込み
    FILE *fp = fopen("/sd/WriteReadTest.txt", "w");
    if (fp == NULL)
    {
        fprintf(stderr, "Open error for writing!!\r\n");
        while (true) {}
    }

    fprintf(fp, "Hello!\n");
    fprintf(fp, "Example of writing and reading of text file.\n");
    fclose(fp);

    // SD から読み出し
    fp = fopen("/sd/WriteReadTest.txt", "r");
    if (fp == NULL)
    {
        fprintf(stderr, "Open error for reading!!\r\n");
        while (true) {}
    }

    printf("String in read file is as follows:\r\n");

    while (true)
    {
        int chr = fgetc(fp);
        if (chr == EOF) break;
        printf("%c", chr);
        if (chr == '\n') printf("\r");
    }

    fclose(fp);
    sd.unmount();    // SD 用

    printf("\r\nSD Text file write/read test: completed\r\n");

    while(true)
    {
        led_green = !led_green;
        wait(0.2f);
    }
}