ESP32 ESP-IDF C语言使用 qsort 对 SD 卡某个目录里面的文件进行排序的例子

#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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值