#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_vfs_fat.h"
#include "driver/sdmmc_host.h"
#include "driver/sdspi_host.h"
#include "driver/gpio.h"
#include "sdmmc_cmd.h"
#define SCRATCH_BUFSIZE (1024)
typedef struct {
char name[32];
uint32_t size;
} file_t;
int compare_file(const void *a, const void *b)
{
return strcmp(((file_t *)a)->name, ((file_t *)b)->name);
}
void list_files(const char *path)
{
DIR *dir = opendir(path);
if (!dir) {
printf("Failed to open directory %s\n", path);
return;
}
struct dirent *entry;
file_t files[100];
int file_count = 0;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { /* If the entry is a regular file */
strcpy(files[file_count].name, entry->d_name);
files[file_count].size = entry->d_size;
file_count++;
}
}
closedir(dir);
qsort(files, file_count, sizeof(file_t), compare_file);
printf("Number of files: %d\n", file_count);
for (int i = 0; i < file_count; i++) {
printf("File: %s, size: %d\n", files[i].name, files[i].size);
}
}
void app_main()
{
ESP_LOGI(TAG, "Initializing SD card");
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
sdspi_slot_config_t slot_config = SDSPI_SLOT_CONFIG_DEFAULT();
gpio_set_pull_mode(15, GPIO_PULLUP_ONLY); // CMD, needed in 4- and 1- line modes
gpio_set_pull_mode(2, GPIO_PULLUP_ONLY); // D0, needed in 4- and 1-line modes
gpio_set_pull_mode(4, GPIO_PULLUP_ONLY); // D1, needed in 4-line modes
gpio_set_pull_mode(12, GPIO_PULLUP_ONLY); // D2, needed in 4-line modes
gpio_set_pull_mode(13, GPIO_PULLUP_ONLY); // D3, needed in 4- and 1-line modes
esp_vfs_fat_sdspi_mount_config_t mount_config = {
.format_if_mount_failed = true,
.max_files = 5,
.allocation_unit_size = 16 * 1024
};
sdmmc_card_t *card;
esp_err_t ret = esp_vfs_fat_sdspi_mount("/sdcard", &host, &slot_config, &mount_config, &card);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
printf("Failed to mount filesystem. "
"If you want the card to be formatted, set format_if_mount_failed = true.\n");
} else {
printf("Failed to initialize the card (%s). "
"Make sure SD card lines have pull-up resistors in place.\n", esp_err_to_name(ret));
}
return;
}
list_files("/sdcard");
}
ESP32 ESP-IDF C语言使用 qsort 对 SD 卡某个目录里面的文件进行排序的例子
最新推荐文章于 2024-05-27 10:19:36 发布