1 /*------------------------------------------------------------/
2 / Delete a sub-directory even if it contains any file
3 /-------------------------------------------------------------/
4 / The delete_node() function is for R0.12+.
5 / It works regardless of FF_FS_RPATH.
6 */
7
8
delete_node(TCHAR * path,UINT sz_buff,FILINFO * fno)9 FRESULT delete_node (
10 TCHAR* path, /* Path name buffer with the sub-directory to delete */
11 UINT sz_buff, /* Size of path name buffer (items) */
12 FILINFO* fno /* Name read buffer */
13 )
14 {
15 UINT i, j;
16 FRESULT fr;
17 DIR dir;
18
19
20 fr = f_opendir(&dir, path); /* Open the sub-directory to make it empty */
21 if (fr != FR_OK) return fr;
22
23 for (i = 0; path[i]; i++) ; /* Get current path length */
24 path[i++] = _T('/');
25
26 for (;;) {
27 fr = f_readdir(&dir, fno); /* Get a directory item */
28 if (fr != FR_OK || !fno->fname[0]) break; /* End of directory? */
29 j = 0;
30 do { /* Make a path name */
31 if (i + j >= sz_buff) { /* Buffer over flow? */
32 fr = 100; break; /* Fails with 100 when buffer overflow */
33 }
34 path[i + j] = fno->fname[j];
35 } while (fno->fname[j++]);
36 if (fno->fattrib & AM_DIR) { /* Item is a sub-directory */
37 fr = delete_node(path, sz_buff, fno);
38 } else { /* Item is a file */
39 fr = f_unlink(path);
40 }
41 if (fr != FR_OK) break;
42 }
43
44 path[--i] = 0; /* Restore the path name */
45 f_closedir(&dir);
46
47 if (fr == FR_OK) fr = f_unlink(path); /* Delete the empty sub-directory */
48 return fr;
49 }
50
51
52
53
main(void)54 int main (void) /* How to use */
55 {
56 FRESULT fr;
57 FATFS fs;
58 TCHAR buff[256];
59 FILINFO fno;
60
61
62 f_mount(&fs, _T("5:"), 0);
63
64 /* Directory to be deleted */
65 _tcscpy(buff, _T("5:dir"));
66
67 /* Delete the directory */
68 fr = delete_node(buff, sizeof buff / sizeof buff[0], &fno);
69
70 /* Check the result */
71 if (fr) {
72 _tprintf(_T("Failed to delete the directory. (%u)\n"), fr);
73 return fr;
74 } else {
75 _tprintf(_T("The directory and the contents have successfully been deleted.\n"), buff);
76 return 0;
77 }
78 }
79
80
81
82