ESP32使用SPIFFS文件系統筆記


基於ESP-IDF4.1

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <sys/unistd.h>
 4 #include <sys/stat.h>
 5 #include "esp_err.h"
 6 #include "esp_log.h"
 7 #include "esp_spiffs.h"
 8 
 9 static const char *TAG = "example";
10 
11 void app_main(void)
12 {
13     ESP_LOGI(TAG, "Initializing SPIFFS");
14 
15     esp_vfs_spiffs_conf_t conf = {
16       .base_path = "/spiffs",
17       .partition_label = NULL,
18       .max_files = 5,
19       .format_if_mount_failed = true
20     };
21 
22     //使用上面定義的設置來初始化和掛在spiffs文件系統
23     esp_err_t ret = esp_vfs_spiffs_register(&conf);
24 
25     if (ret != ESP_OK) {
26         if (ret == ESP_FAIL) {
27             ESP_LOGE(TAG, "Failed to mount or format filesystem");
28         } else if (ret == ESP_ERR_NOT_FOUND) {
29             ESP_LOGE(TAG, "Failed to find SPIFFS partition");
30         } else {
31             ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
32         }
33         return;
34     }
35 
36     size_t total = 0, used = 0;
37     ret = esp_spiffs_info(conf.partition_label, &total, &used);
38     if (ret != ESP_OK) {
39         ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s)", esp_err_to_name(ret));
40     } else {
41         ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
42     }
43 
44     //使用POSIX和C標准庫函數操作文件
45     //創建一個文件
46     ESP_LOGI(TAG, "Opening file");
47     FILE* f = fopen("/spiffs/hello.txt", "w"); // 打開只寫文件,若文件存在則文件長度清為0,即該文件內容會消失。若文件不存在則建立該文件。
48     if (f == NULL) {
49         ESP_LOGE(TAG, "Failed to open file for writing");
50         return;
51     }
52     fprintf(f, "Hello World!\n");
53     fclose(f);
54     ESP_LOGI(TAG, "File written");
55 
56     //重命名前檢查目標文件是否存在
57     struct stat st;
58     if (stat("/spiffs/foo.txt", &st) == 0) {
59         // 如果存在則刪除
60         unlink("/spiffs/foo.txt");
61     }
62 
63     // 重命名原始文件
64     ESP_LOGI(TAG, "Renaming file");
65     if (rename("/spiffs/hello.txt", "/spiffs/foo.txt") != 0) {
66         ESP_LOGE(TAG, "Rename failed");
67         return;
68     }
69 
70     // 打開重命名的文件
71     ESP_LOGI(TAG, "Reading file");
72     f = fopen("/spiffs/foo.txt", "r"); // 以只讀方式打開文件
73     if (f == NULL) {
74         ESP_LOGE(TAG, "Failed to open file for reading");
75         return;
76     }
77     char line[64];
78     //從指定的流 f 讀取一行,並把它存儲在 line 所指向的字符串內
79     fgets(line, sizeof(line), f); 
80     fclose(f);
81     // 查找換行符
82     char* pos = strchr(line, '\n');
83     if (pos) {
84         *pos = '\0'; //放置一個空字符串
85     }
86     ESP_LOGI(TAG, "Read from file: '%s'", line);
87 
88     // 卸載分區並禁用SPIFFS
89     esp_vfs_spiffs_unregister(conf.partition_label);
90     ESP_LOGI(TAG, "SPIFFS unmounted");
91 }

 

原文:https://gitee.com/EspressifSystems/esp-idf


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM