#include "common.h"
#include <string.h>
FRESULT scan_files (char* path);
#define F_PUTS 1 //测试向文件写入字符串
#define F_READ 1 //测试从文件中读出数据
#define F_UNLINK 0 //测试删除文件
#define SCAN_FILES 1 //测试目录扫描
FATFS fs;
FRESULT res;
FIL file;
UINT br;
BYTE buffer[4096]; //以上变量作为全局变量 可以避免一些Bug
int main(void)
{
u16 i,n;
//stm32 初始化
RCC_Configuration();
NVIC_Configuration();
USART_Configuration();
SPI_Configuration();
GPIO_Configuration();
//fatfs 操作
f_mount(0, &fs);
//如果data.txt存在,则打开;否则,创建一个新文件
res = f_open(&file, "0:/data.txt",FA_OPEN_ALWAYS|FA_READ|FA_WRITE );
if(res!=FR_OK)
{
printf("\r\n f_open() fail .. \r\n");
}else{
printf("\r\n f_open() success .. \r\n");
}
#if F_READ
while(1){ //使用f_read读文件
res = f_read(&file, buffer, 1, &br); //一次读一个字节知道读完全部文件信息
if (res == FR_OK )
{
printf("%s",buffer);
}else{
printf("\r\n f_read() fail .. \r\n");
}
if(f_eof(&file)) {break;}
}
/*if( f_gets(buffer,sizeof(buffer),&file) != NULL) //使用f_gets读文件 ,存在 Bugs 待调试
{
printf("%s",buffer);
}else{
printf("\r\n f_gets() fail .. \r\n");
} */
#endif
#if F_PUTS
//将指针指向文件末
//res = f_lseek(&file,(&file)->fsize);
res = f_lseek(&file,file.fsize);
n = f_puts("\r\n hello dog ..\r\n", &file) ; //向文件末写入字符串
if(n<1) //判断写是否成功
{
printf("\r\n f_puts() fail .. \r\n");
}else{
printf("\r\n f_puts() success .. \r\n");
}
#endif
#if F_UNLINK
res = f_unlink("test.jpg"); //前提SD下存在一个test.jpg
if(res!=FR_OK)
{
printf("\r\n f_unlink() fail .. \r\n");
}else{
printf("\r\n f_unlink() success .. \r\n");
}
#endif
#if SCAN_FILES
printf("\r\n the directory files : \r\n");
scan_files("/"); //扫描根目录
#endif
f_close(&file);
f_mount(0, NULL);
while(1);
}
FRESULT scan_files (
char* path /* Start node to be scanned (also used as work area) */
)
{
FRESULT res;
FILINFO fno;
DIR dir;
int i;
char *fn; /* This function is assuming non-Unicode cfg. */
#if _USE_LFN
static char lfn[_MAX_LFN + 1];
fno.lfname = lfn;
fno.lfsize = sizeof lfn;
#endif
res = f_opendir(&dir, path); /* Open the directory */
if (res == FR_OK) {
i = strlen(path);
for (;;) {
res = f_readdir(&dir, &fno); /* Read a directory item */
if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */
if (fno.fname[0] == '.') continue; /* Ignore dot entry */
#if _USE_LFN
fn = *fno.lfname ? fno.lfname : fno.fname;
#else
fn = fno.fname;
#endif
if (fno.fattrib & AM_DIR) { /* It is a directory */
sprintf(&path[i], "/%s", fn);
res = scan_files(path);
if (res != FR_OK) break;
path[i] = 0;
} else { /* It is a file. */
printf("\r\n %s/%s \r\n", path, fn);
}
}
}
return res;
}
Fatfs 文件系统减轻了操作SD卡的工作量,调用其提供的函数就可以方便的操作文件,读写删改等。
这里提供一个main.c 示例: |