![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
dsfa
Dependencies: dsf SDFileSystem TextLCD mbed stepper_moter
Fork of my_example_Nucleo_Ex05_SD_zhangyuxiang2 by
Diff: main.cpp
- Revision:
- 1:d65338ce2e7c
- Parent:
- 0:b0a3ecd53c7d
- Child:
- 2:1c1602268656
diff -r b0a3ecd53c7d -r d65338ce2e7c main.cpp --- a/main.cpp Mon Mar 21 08:58:22 2016 +0000 +++ b/main.cpp Wed Aug 23 03:11:41 2017 +0000 @@ -1,46 +1,40 @@ #include "mbed.h" #include "SDFileSystem.h" -DigitalIn btn(USER_BUTTON); - -// trim '\n' -void ntrim(char *str) -{ - int i; - for (i = 0; str[i] != 0; ++i); - - if (i > 0 && str[i - 1] == '\n') - str[i - 1] = 0; -} +// mosi, miso, sclk, name +SDFileSystem sd(PB_15, PB_14, PB_13, PA_9, "sd"); int main() { - // SD filesystem - SDFileSystem *sd = new SDFileSystem(PB_15, PB_14, PB_13, PA_9, "sd", NC, SDFileSystem::SWITCH_NONE, 20000000); // mosi, miso, sclk, name, card detect, sw type, freq - - while (1) - { - if (btn) continue; + // 读文件例子 + FILE *fp = fopen("/sd/test.txt", "r"); //打开文件,路径以“/sd/”开头 - // file open - FILE *fp = fopen("/sd/test.txt", "r"); - if (fp == NULL) - { - printf("open error!!\r\n"); - while(1); - } - - // read text file - char buf[1024]; - while (fgets(buf, sizeof(buf), fp) != NULL) - { - ntrim(buf); - printf("%s\r\n", buf); - } + if (fp == NULL) //打开失败,原因可能是文件不存在,或卡没有连接好 + { + printf("open error!!\r\n"); + return 1; + } + printf("file opened for read\r\n"); + char buf[64]; + while (fgets(buf, sizeof(buf), fp) != NULL) //读入一行的C函数 + { + printf("read '%s'\r\n", buf); + } + fclose(fp); //关闭文件,释放资源 + + //printf("card type is 0x%x\r\n" , sd.card_type()); - // file close - fclose(fp); + // 写文件例子 + FILE *fp2 = fopen("/sd/write.txt", "w"); + if (fp2 == NULL) + { + printf("open error2!!\r\n"); + return 1; + } + printf("file opened for write\r\n"); + fprintf(fp2, "hello\r\n"); + fprintf(fp2, "%d", 23333); + fclose(fp2); //写完文件要记得关闭,不然可能没保存上 - wait(1); - } + return 0; }