FATFS文件系统读写案例,亲测有效
自己 本来想写一个stm32移植FATFS文件系统进行存取数据
但网上能够参照的实例,实在太少,而且出现的问题还挺多
于是花费了很长一段时间才将读写问题解决
希望能够对一些想要进行FATFS的操作的小伙伴有一定的帮助
代码如下
FIL fw;
FRESULT res;
struct Struct_Pack Pack_Fram[5] = {'0',"----",'1',"----",'2',"----",'3',"----",'4',"----"};
void CreatPackFile(struct Struct_Pack *dat)
{
u8 i = 0,j = 0;
UINT br;
char p[1024];
printf("Strart");
res = f_open(file,"0:pack.txt",FA_OPEN_ALWAYS | FA_READ | FA_WRITE);
if(res == FR_OK)
{
printf("OK");
//指针往后移
f_lseek(file,0);
//获取数据
res = f_read(file,p,sizeof(p),&br);
if(res == FR_OK)
{
if(p[0] != '\0')
{
for(i = 0; i < 5; i++)
{
dat[i].num = p[i * 5];
for(j = 0; j < 5; j++)
{
dat[i].getNum[j] = p[i * 5 + j + 1];
}
}
}
}
f_close(file);
}
else
{
printf("Err");
}
}
void SavaData(struct Struct_Pack *dat)
{
UINT bw;
char write_buff[1024];
u8 i,j;
for(i = 0; i < 5; i++)
{
write_buff[i * 5] = dat[i].num;
for(j = 0; j < 5; j++)
{
write_buff[i * 5 + j + 1] = dat[i].getNum[j];
}
}
write_buff[25] = '\0';
res = f_open(&fw,"0:pack.txt",FA_OPEN_EXISTING | FA_READ | FA_WRITE);
if(res == FR_OK)
{
f_lseek(&fw,0);
res = f_write(&fw,write_buff,sizeof(write_buff),&bw);
if(res == FR_OK)
{
printf("保存成功\r\n");
}
else
{
printf("保存失败%d\r\n",res);
}
f_close(&fw);
}
else
{
printf("打开失败\r\n");
}
}
最后强调两个问题
读写缓冲区read_buffer write_buffer不要随意设置(否则文件必读写不了)
FIL要一定设置成全局变量(否则程序必跑飞)