Directory Access Functions - POSIX
The directory access functions provide an API for iterating through the entries within a directory. The fs_opendir()
function initiates this procedure, and each subsequent call to fs_readdir_r()
(until all entries have been examined) returns information about a particular entry in a struct fs_dirent. The fs_closedir()
function releases any file system structures and locks.
Listing - Directory listing example code gives an example using the directory access functions to list the files in a directory.
void App_Fnct (void) { FS_DIR *p_dir; struct fs_dirent dirent; struct fs_dirent *p_dirent; char str[50]; char *p_cwd_path; fs_time_t ts; . . . p_dir = fs_opendir(p_cwd_path); /* Open dir. */ if (p_dir != (FS_DIR *)0) { (void)fs_readdir_r(pdir, &dirent, &p_dirent); /* Rd first dir entry. */ if (p_dirent == (FS_DIRENT *)0) { /* If NULL ... dir is empty. */ APP_TRACE_INFO(("Empty dir: %s.\r\n", p_cwd_path)); } else { /* Fmt info for each entry. */ Str_Copy(str, "-r--r—r-- : "); while (p_dirent != (struct dirent *)0) { /* Chk if file is dir. */ if (DEF_BIT_IS_SET(dirent.Info.Attrib, FS_ENTRY_ATTRIB_DIR) == DEF_YES) { str[0] = 'd'; } /* Chk if file is rd only. */ if (DEF_BIT_IS_SET(dirent.Info.Attrib, FS_ENTRY_ATTRIB_WR) == DEF_YES) { str[2] = 'w'; str[5] = 'w'; str[8] = 'w'; } /* Get file size. */ if (p_dirent->Info.Size == 0) { if (DEF_BIT_IS_CLR(dirent.Info.Attrib, FS_ENTRY_ATTRIB_DIR) == DEF_YES) { Str_Copy(&str[11]," 0"); } } else { Str_FmtNbr_Int32U(dirent.Info.Size, 10, 10, '0', DEF_NO, DEF_NO, &str[11]); } /* Get file date/time. */ if (p_dirent->Info.DateTimeCreate.Month != 0) { Str_Copy(&str[22], (CPU_CHAR *)App_MonthNames[dirent.Info.DateTimeCreate.Month - 1]); Str_FmtNbr_Int32U(dirent.Info.DateTimeWr.Day, 2, 10, ' ', DEF_NO, DEF_NO, &str[26]); Str_FmtNbr_Int32U(dirent.Info.DateTimeWr.Hour, 2, 10, ' ', DEF_NO, DEF_NO, &str[29]); Str_FmtNbr_Int32U(dirent.Info.DateTimeWr.Minute, 2, 10, ' ', DEF_NO, DEF_NO, &str[32]); } /* Output info for entry. */ APP_TRACE_INFO(("%s%s\r\n", str, dirent.Name)); /* Rd next dir entry. */ (void)fs_readdir_r(pdir, &dirent, &p_dirent); } } fs_closedir(p_dir); /* Close dir. */ /* If dir could not be opened ... */ } else { /* ... dir does not exist. */ APP_TRACE_INFO(("Dir does not exist: %s.\r\n", p_cwd_path)); } . . . }
An example result of listing a directory is shown in the figure below.
The second argument fs_readdir_r()
, is a pointer to a struct fs_dirent
, which has two members. The first is Name, which holds the name of the entry; the second is Info, which has file information. For more information about the struct fs_dirent
structure, see FS_DIR_ENTRY (struct fs_dirent).