文章目录
- 1、打开文件夹
- 2、读取文件夹
- 3、打开\新建一个文件
- 5、读取文件
1、打开文件夹
FRESULT f_opendir (
DIR* DirObject, /* Pointer to the blank directory object
structure */
const TCHAR* DirName /* Pointer to the directory name */
)
函数说明:
- 此函数可以打开一个已存在的文件夹
- 参数说明:
a) *DirObject : 指向一个空白的结构体,用来存储要打开的文件夹信息
b) *DirName : 指向该文件夹名称的指针
2、读取文件夹
FRESULT f_readdir (
DIR* DirObject, /* Pointer to the open directory object */
FILINFO* FileInfo /* Pointer to the file information structure */
);
函数说明:
- 此函数按照顺序读取文件夹内文件
- 参数说明:
a) *DirObject : 指向读取的文件夹的信息结构体的指针
b) *FileInfo : 指向文件信息结构体,用来存储读取到的文件的信息 - 重复调用此函数可读取文件夹内所有文件
- 当所有文件读取结束,函数返回一个空字符串到 f_name[] 中
- 如果一个空指针赋给 *FileInfo ,将返回从第一个文件开始读取.
例程:这段程序先打开文件夹 folde/move ,然后查找其中的存档文件,并通过串口输出
读取的文件名
if (f_opendir(&dirs, "folder/move") == FR_OK) //打开文件夹
{
while (f_readdir(&dirs, &finfo) == FR_OK) //按照顺序读文件夹
{
if(!finfo.fname[0]) break; //如果文件名为 0,结束
{
if(finfo.fattrib == AM_ARC) //判断文件属性
Debug("文件名:%s\r\n",finfo.fname);
}
}
}
串口输出如下:
在 PC 上查看 SD 卡:
if(finfo.fattrib == AM_ARC),意思是只对存档文件进行处理;
3、打开\新建一个文件
FRESULT f_open (
FIL* FileObject, /* Pointer to the blank file object structure
*/
const TCHAR* FileName, /* Pointer to the file neme */
BYTE ModeFlags /* Mode flags */
);
函数说明:
- 此函数可以打开,或新建一个文件
- 参数说明
a) *FileObject : 指向一个用来存储文件对象的空结构体的指针
b) *FileName : 指向文件名的指针
c) ModeFlags : 打 开 方 式 , 可 以 是 以 下 一 种 或 几 种 的 组 合 ( 默 认 方 式 是FA_OPEN_EXISTING)
5、读取文件
FRESULT f_read (
FIL* FileObject, /* Pointer to the file object structure */
void* Buffer, /* Pointer to the buffer to store read data */
UINT ByteToRead, /* Number of bytes to read */
UINT* ByteRead /* Pointer to the variable to return number of bytes
read */
);
函数说明:
1. 这个函数可以读取文件的内容
2. 参数说明:
a) *FileObject : 指向文件对象结构体的指针
b) *Buffer : 指向存储读取到的数据的缓冲的指针
c) ByteToRead : 准备读取的字节数
d) *ByteRead :
i. 它的作用就是用来检测文件的末尾,就是下面例程中的这一句:
if (res || br < sizeof(buffer)) break;
ii. 每次 f_read 执行完后,ByteRead 值等于本次读取到的字节数,若ByteRead
<ByteToRead,即本次读取到的字节小于准备读取的字节,说明读指针已到达
文件末尾.
例程:此处参考酷学玩例程,以读取的方式打开文件,然后将文件内容通过串口输出。
res = f_open(&fsrc, "news/news.txt", FA_READ);
if(!res)
{
Debug("open news/news.txt : %d\r\n",res);
br=1;
a=0;
Debug("文件内容:");
for (;;)
{
for(a=0; a<512; a++) buffer[a]=0;
res = f_read(&fsrc, buffer, sizeof(buffer), &br);
Debug("%s\r\n",buffer);
if (res || br < sizeof(buffer)) break; // error or eof
}
}
f_close(&fsrc); //不论是打开,还是新建文件,一定记得关闭
运行后串口输出结果:
下面是在PC中查看: