bakalarka/components/files/file.c

85 lines
2.1 KiB
C
Raw Normal View History

2020-03-20 17:01:25 +00:00
#include <stdio.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_spiffs.h"
#include "file.h"
static const char *TAG = "SPIFFS";
2020-03-31 16:12:53 +00:00
/*Register and mount SPIFFS to VFS with given path prefix*/
2020-03-20 17:01:25 +00:00
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = "storage_spiffs",
2020-03-31 16:12:53 +00:00
.max_files = 20,
2020-03-20 17:01:25 +00:00
.format_if_mount_failed = true
};
void init_memory(){
ESP_LOGI(TAG, "Initializing SPIFFS");
// Use settings defined above to initialize and mount SPIFFS filesystem.
// Note: esp_vfs_spiffs_register is an all-in-one convenience function.
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount or format filesystem");
} else if (ret == ESP_ERR_NOT_FOUND) {
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
} else {
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
}
return;
}
size_t total = 0, used = 0;
ret = esp_spiffs_info(conf.partition_label, &total, &used);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s)", esp_err_to_name(ret));
} else {
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
}
}
void close_memory(){
esp_vfs_spiffs_unregister(conf.partition_label);
ESP_LOGI(TAG, "SPIFFS unmounted");
}
void create_file(char adresa[],char comment[]){
ESP_LOGI(TAG, "Opening file");
FILE* f = fopen(adresa, "w");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for writing");
return;
}
fprintf(f, comment);
fclose(f);
ESP_LOGI(TAG, "File written");
2020-03-30 11:21:12 +00:00
2020-03-20 17:01:25 +00:00
}
void read_file(char adresa[]){
char line[120];
ESP_LOGI(TAG, "Reading file");
FILE* f = fopen(adresa, "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for reading");
return;
}
ESP_LOGI(TAG, "Read from file: ");
while(fgets(line, 120, f)){
printf("%s",line);
}
fclose(f);
2020-03-31 16:12:53 +00:00
2020-03-20 17:01:25 +00:00
}