硬汉嵌入式论坛

 找回密码
 立即注册
查看: 129|回复: 2
收起左侧

[FatFs] FatFS删除非空文件夹的方法

[复制链接]

1万

主题

7万

回帖

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
118308
QQ
发表于 2025-9-17 10:49:33 | 显示全部楼层 |阅读模式
elm-chan.org/fsw/ff/res/app2.c


[C] 纯文本查看 复制代码
/*------------------------------------------------------------/
/ Delete a sub-directory even if it contains any file
/-------------------------------------------------------------/
/ The delete_node() function is for R0.12+.
/ It works regardless of FF_FS_RPATH.
*/


FRESULT delete_node (
    TCHAR* path,    /* Path name buffer with the sub-directory to delete */
    UINT sz_buff,   /* Size of path name buffer (items) */
    FILINFO* fno    /* Name read buffer */
)
{
    UINT i, j;
    FRESULT fr;
    DIR dir;


    fr = f_opendir(&dir, path); /* Open the sub-directory to make it empty */
    if (fr != FR_OK) return fr;

    for (i = 0; path[i]; i++) ; /* Get current path length */
    path[i++] = _T('/');

    for (;;) {
        fr = f_readdir(&dir, fno);  /* Get a directory item */
        if (fr != FR_OK || !fno->fname[0]) break;   /* End of directory? */
        j = 0;
        do {    /* Make a path name */
            if (i + j >= sz_buff) { /* Buffer over flow? */
                fr = 100; break;    /* Fails with 100 when buffer overflow */
            }
            path[i + j] = fno->fname[j];
        } while (fno->fname[j++]);
        if (fno->fattrib & AM_DIR) {    /* Item is a sub-directory */
            fr = delete_node(path, sz_buff, fno);
        } else {                        /* Item is a file */
            fr = f_unlink(path);
        }
        if (fr != FR_OK) break;
    }

    path[--i] = 0;  /* Restore the path name */
    f_closedir(&dir);

    if (fr == FR_OK) fr = f_unlink(path);  /* Delete the empty sub-directory */
    return fr;
}




int main (void) /* How to use */
{
    FRESULT fr;
    FATFS fs;
    TCHAR buff[256];
    FILINFO fno;


    f_mount(&fs, _T("5:"), 0);

    /* Directory to be deleted */
    _tcscpy(buff, _T("5:dir"));

    /* Delete the directory */
    fr = delete_node(buff, sizeof buff / sizeof buff[0], &fno);

    /* Check the result */
    if (fr) {
        _tprintf(_T("Failed to delete the directory. (%u)\n"), fr);
        return fr;
    } else {
        _tprintf(_T("The directory and the contents have successfully been deleted.\n"), buff);
        return 0;
    }
}



回复

使用道具 举报

12

主题

149

回帖

185

积分

初级会员

积分
185
发表于 2025-9-17 11:41:20 | 显示全部楼层
递归调用,早晚崩溃
回复

使用道具 举报

1万

主题

7万

回帖

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
118308
QQ
 楼主| 发表于 2025-9-18 11:26:08 | 显示全部楼层
lvehe 发表于 2025-9-17 11:41
递归调用,早晚崩溃

嵌套确实不安全,子嵌套文件夹多了确实麻烦。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|小黑屋|Archiver|手机版|硬汉嵌入式论坛

GMT+8, 2025-9-26 09:20 , Processed in 0.044902 second(s), 24 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表