根据论坛的帖子http://www.51hei.com/bbs/dpj-88507-1.html
自己移植了最新版FATS 0.13a
测试成功,可以读写文件,追加文件。
部分代码如下
- void SD_ReadTest(void)
- {
- unsigned int offset = 0;
- disk_initialize(DEV_MMC);
- res = f_mount(&fs,"1:",0); // 挂载
- res = f_open(&fsrc,"1:/KILLL.BAT",FA_OPEN_EXISTING | FA_READ); // 打开文件
- if(res != FR_OK)
- {
- printf("%d ",res);
- printf("open error\r\n");
- }
- else
- {
- file_size = f_size(&fsrc);
- printf("filesize:%d\r\n",file_size);
- do{
- res = f_lseek(&fsrc,offset); // 指针往后推128
- res = f_read(&fsrc,buffer,sizeof(buffer),&br);
- if(res == FR_OK)
- {
- USART1_SendBuf(buffer,br);
- printf("\r\n");
- }
- else
- {
- printf("read fils err\r\n");
- }
- offset += 128;
- file_size -= 128;
- }while(file_size>128);
- if(file_size>0)
- {
- res = f_read(&fsrc,buffer,file_size,&br);
- if(res == FR_OK)
- {
- USART1_SendBuf(buffer,br);
- printf("EndOfFile\r\n");
- }
- else
- {
- printf("read fils err\r\n");
- }
- }
- f_close(&fsrc);// 关闭文件
- }
- f_mount(NULL,"1:",0); //卸载磁盘
- }
复制代码 获取文件长度并串口输出文件内容,适用于读取bin文件做系统软件升级IAP.
- FRESULT open_append (
- FIL* fp, /* [OUT] File object to create */
- const char* path /* [IN] File name to be opened */
- )
- {
- FRESULT fr;
- /* Opens an existing file. If not exist, creates a new file. */
- fr = f_open(fp, path, FA_WRITE | FA_OPEN_ALWAYS);
- if (fr == FR_OK) {
- /* Seek to end of the file to append data */
- fr = f_lseek(fp, f_size(fp));
- if (fr != FR_OK)
- f_close(fp);
- }
- return fr;
- }
- void SD_WriteTest(void)
- {
- unsigned char write_f[20]={"ming write file test"};
- disk_initialize(0);
- res = f_mount(&fs,"1:",0);
- res = open_append(&fdst,"1:/testa.txt");
-
- // res = f_open(&fdst, "1:/testa.txt", FA_CREATE_ALWAYS | FA_WRITE);
- if(res != FR_OK)
- {
- printf("open error\r\n");
- }
- else
- {
- f_printf(&fdst, "%d\n", runtime);
- //res = f_write(&fdst,write_f,sizeof(write_f),&bw);
- //res = f_puts("hello",&fdst);
- if(res <0)
- {
- printf("write err! %d\r\n",res);
- }
- else
- {
- printf("write ok! %d\r\n",res);
- }
- f_close(&fdst);
- }
- f_mount(NULL,"1:",0);// 卸载
- printf("write test passed! \r\n");
- }
复制代码 文件内容追加,适合保存日志log
- void ReadSDFile(void)
- {
- // FIL file;
- FILINFO finfo;
- DIR dirs;
- int i_name=0;
- // char *fn;
- f_mount(&fs,"1:",1);
- res = f_opendir(&dirs, "1:/");
- if (res == FR_OK)
- {
- while (f_readdir(&dirs, &finfo) == FR_OK)
- {
- if (finfo.fattrib & AM_ARC)
- {
- if(!finfo.fname[0]) break; //文件名不为空,如果为空,则表明该目录下面的文件已经读完了
- stringcopy(buff_filename[i_name], (BYTE*)finfo.fname);
- i_name++;
- file_cnt = i_name;
- }
- }
- f_close(&fsrc);
- i_name = 0;
- do{
- //USART1_SendBuf(buff_filename[i_name],br);
- printf("%s\r\n",buff_filename[i_name]);
- i_name++;
- file_cnt--;
- }while(file_cnt);
- }
- f_mount(NULL,"1:",1);
- }
复制代码 获取文件列表。
STM32_SDIO_FAT13.zip
(1.44 MB, 下载次数: 39)
如果需要解压密码,请双击压缩包或右键压缩包查看注释。
|