//注意需要在配置文件中显式定义定义littlefs
#include <LittleFS.h>
String file_name = "/taichi-maker/notes.txt"; //被读取的文件位置和名称
String folder_name = "/taichi-maker"; //被读取的文件夹
String write_info = "Hello,this is Kafen";
String append_info = "Hello,this is Kafen append";
boolean fs_init();//init a filesystem
boolean file_write(String file_name,String write_info);//write to a file
boolean file_read(String file_name);
boolean file_append(String file_name,String append_info);
boolean file_check_dir(String folder_name);
boolean file_remove(String file_name);
boolean file_showinfo();
void setup() {
Serial.begin(9600);
Serial.println("");
fs_init();
file_write( file_name,write_info);
file_append(file_name,append_info);
file_read(file_name);
file_remove( file_name);
file_showinfo();
}
void loop() {
}
boolean fs_init(){
Serial.println("LittleFS format start");
LittleFS.format(); // 格式化LittleFS
Serial.println("LittleFS format finish");
return LittleFS.begin()?true:false; //返回值
}
boolean file_write(String file_name,String write_info){ //write in file
File dataFile = LittleFS.open(file_name, "w");// 建立File对象用于向LittleFS中的file对象(即/notes.txt)写入信息
dataFile.println(write_info); // 向dataFile写入字符串信息
dataFile.close(); // 完成文件写入后关闭文件
Serial.println("Finished Writing data to LittleFS");
return true;
}
boolean file_read(String file_name){
File dataFile =LittleFS.open(file_name, "r");
for(int i=0; i<dataFile.size(); i++){
Serial.print((char)dataFile.read());
}
dataFile.close();
return true;
}
boolean file_append(String file_name,String append_info){
File dataFile = LittleFS.open(file_name, "a");// 建立File对象用于向SPIFFS中的file对象(即/notes.txt)写入信息
dataFile.println(append_info); // 向dataFile添加字符串信息
dataFile.close(); // 完成文件操作后关闭文件
Serial.println("Finished Appending data to SPIFFS");
file_check_dir(folder_name);
return LittleFS.exists(file_name) ? true: false;
}
boolean file_check_dir(String folder_name){
Dir dir = LittleFS.openDir(folder_name); // 建立“目录”对象
while (dir.next()) { // dir.next()用于检查目录中是否还有“下一个文件”
Serial.println(dir.fileName()); // 输出文件名
}
return true;
}
boolean file_remove(String file_name){
return LittleFS.remove(file_name)?true:false;
}
boolean file_showinfo(){
FSInfo fs_info;
LittleFS.info(fs_info);
// 可用空间总和(单位:字节)
Serial.print("totalBytes: ");
Serial.print(fs_info.totalBytes);
Serial.println(" Bytes");
// 已用空间(单位:字节)
Serial.print("usedBytes: ");
Serial.print(fs_info.usedBytes);
Serial.println(" Bytes");
// 最大文件名字符限制(含路径和'\0')
Serial.print("maxPathLength: ");
Serial.println(fs_info.maxPathLength);
// 最多允许打开文件数量
Serial.print("maxOpenFiles: ");
Serial.println(fs_info.maxOpenFiles);
// 存储块大小
Serial.print("blockSize: ");
Serial.println(fs_info.blockSize);
// 存储页大小
Serial.print("pageSize: ");
Serial.println(fs_info.pageSize);
return true;
}
01-01
1183
09-28
689
05-15
1967